#!/usr/bin/env python

import numpy as np
from glob import glob
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from astropy.timeseries import LombScargle as ls
from scipy.signal import find_peaks
from phot2lc.photfunc import calc_lsp, prewhiten

"""
A tool which generates a plot of the lightcurve
from an available .lc file generated by phot2lc,
or a .lc1 file generated by WQED.

In addition to the lightcurve, a periodogram
is also generated and a pre-whitening sequence
is automatically run to identify significant
peaks.


Author:
    Zach Vanderbosch

For a description of updates, see the 
version_history.txt file.
"""

# Load in the divided light curve
lcname = glob('*.lc')
if len(lcname) == 0:
    lcname = glob('*.lc1')
    data = np.loadtxt(lcname[0])
    time = data[:,0]
    flux = data[:,1]
    new = False
else:
    data = np.loadtxt(lcname[0])
    time = data[:,1]
    flux = data[:,2]
    new = True

# Get object name
with open(lcname[0]) as f:
    for l in f.readlines():
        if l[0] == "#":
            if new:
                if "Object" in l.split(":")[0]:
                    object_name = l.split(":")[1].split("#")[0].strip()
                if "Date" in l.split(":")[0]:
                    date_obs = l.split(":")[1].split("#")[0].strip()
            else:
                if "Object" in l.split("=")[0]:
                    object_name = l.split("=")[1].split("#")[0].strip()
                if "Date" in l.split("=")[0]:
                    date_obs = l.split("=")[1].split("#")[0].strip()
        else:
            break

# Calculate the Lomb-Scargle Periodogram
farr,lsp = calc_lsp(time,flux)

# Extract frequency and amplitude values from LMFIT result
result,sig = prewhiten(time,flux)
if result is not None:
    # Save Fit Results
    freq_vals = []
    freq_errs = []
    amp_vals = []
    amp_errs = []
    for name,param in result.params.items():
        if 'freq' in name:
            freq_vals.append(param.value)
            freq_errs.append(param.stderr)
        if 'amp' in name:
            amp_vals.append(abs(param.value))
            amp_errs.append(param.stderr)
    Np = len(freq_vals)
else: 
    Np = 0



# Plotting Code

fig = plt.figure('a',figsize=(8,6))
gs = GridSpec(2,1)
ax0 = fig.add_subplot(gs[0])
ax1 = fig.add_subplot(gs[1])

ax0.plot(time/3600,flux*1e2,ls='None',marker='.',ms=5,mfc='k',mec='k')
ax1.plot(farr*1e6,lsp*1e2,c='k',lw=1)
ax1.axhline(sig*1e2,ls=':',c='C2')

# Set XY Labels
ax0.set_xlabel('Time (hr)',fontsize=10)
ax1.set_xlabel(r'Frequency ($\mu$Hz)',fontsize=10)
ax0.set_ylabel('Relative Flux (%)',fontsize=10)
ax1.set_ylabel('Amplitude (%)',fontsize=10)

# Set XY Limits
amax = max(lsp[farr<0.01]) * 1e2
if amax < sig*1e2:
    yupp = 1.4 * sig*1e2
else:
    yupp = 1.2 * amax
ax1.set_xlim(0,12000)
ax1.set_ylim(0,yupp)

# Add text for 4<A> sig-threshold
threshold_text = r'$4\langle$A$\rangle = {:.2f} \%$'.format(sig*1e2)
ax1.text(8000,sig*1e2+0.04*yupp,threshold_text, color='g',fontsize=10)

# Add Markers for Each Frequency
if Np > 0:
    for i,f in enumerate(freq_vals):
        ax1.plot(f*1e6,1.09*amax,ls='None',marker='|',mfc='r',mec='r',mew=0.5)
        ax1.text(f*1e6,1.13*amax,'{}'.format(i+1),ha='center',fontsize=7,color='r')

# Print out Each Peaks Frequency and Amplitude
font = {'fontname':'Bitstream Vera Sans Mono'}
if Np > 0:
    ax1.text(6000,1.10*amax,'Significant Peaks',fontsize=8,**font)
    ax1.text(6000,1.09*amax,'___________________',**font)
    for i,(f,a) in enumerate(zip(freq_vals,amp_vals)):
        yloc = 1.0*amax - (float(i)*0.08*amax)
        ax1.text(6000,yloc,'{}: {:6.1f} $\mu$Hz  {:5.2f} %'.format(i+1,f*1e6,a*1e2),
                 fontsize=8,**font)


# Add a title
title = "Quicklook Plot for {} on {}".format(object_name,date_obs)
ax0.set_title(title,fontsize=13)

# Set Tick Parameters
ax0.minorticks_on()
ax1.minorticks_on()
ax0.tick_params(which='both',axis='both',top=True,right=True,direction='in')
ax1.tick_params(which='both',axis='both',right=True)

plt.savefig('quicklook_{}.pdf'.format(object_name),bbox_inches='tight')

plt.show()

