#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-

# ATTENTION: necessary to install pdfrw library (sudo port install py27-pdfrw)

import matplotlib as mpl
mpl.use('Agg') # necessary to be able to generate the reports even without X server
import matplotlib.pyplot as plt

import sys
import datetime
import numpy as np
from . import gravi_visual_class

#==============================================================================
# Preparation of the report using reportlab
#==============================================================================
def produce_profile_report(profile,filename):
    # From gravi_visual_class
    from . import gravi_visual_class
    from .gravi_visual_class import PdfImage, myFirstPage, myLaterPages, styles
    from .gravi_visual_class import clipdata, transbarchartout, graphoutaxes, graphoutnoaxis
    from .gravi_visual_class import graphoutnoxaxes, graphscatteraxes, graphaxesplt
    from .gravi_visual_class import plotTitle, plotSubtitle
    from .gravi_visual_class import get_key_withdefault, create_array_from_list, baseline_phases
    from .gravi_visual_class import mean_angle, std_angle, clean_unwrap_phase, nanaverage
    from .gravi_visual_class import clean_gdelay_is, clean_gdelay_fft, clean_gdelay_full
    from .gravi_visual_class import base_list, tel_list, nbase, ntel
    from .gravi_visual_class import plotReductionSummary, plotSummary

    # From reportlab
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, PageBreak
    from reportlab.graphics.shapes import String
    from reportlab.lib.units import inch, cm, mm
    from reportlab.lib import colors
    
    # import PIL
    import io
    from io import StringIO
    
    #==============================================================================
    # Start Story
    #==============================================================================

    Story = [Spacer(1,1*mm)]
    plotSummary (Story, filename, profile, onTarget=False)
    Story.append(Spacer(1,3*cm))
    
    #==============================================================================
    # Science combiner photometry vertical cut
    #==============================================================================

    plotTitle(Story,"Science Combiner average FLAT (vertical average cut)")
    plotSubtitle(Story,"In ADU, average over all wavelengths, x axis in pixels.")
        
    hsize = 16*cm
    vsize = 6*cm
    # Grand average transmission
    minx = 0
    maxx = profile.imaging_data_sc.shape[1]
    cut_avg_sc = np.mean(profile.imaging_data_sc[:,minx:maxx],axis=1)

    pixscale = list(range(0,cut_avg_sc.shape[0]))
    yminval = np.min(cut_avg_sc)
    ymaxval = np.max(cut_avg_sc)
    ticky = (ymaxval-yminval)/5.

    data = []
    data.append( tuple(zip(pixscale, clipdata(cut_avg_sc,yminval,ymaxval))))
    a = graphoutaxes(data, np.min(pixscale), np.max(pixscale), None, yminval, ymaxval, None, hsize, vsize, None, ticky,'')
    Story.append(a)

    Story.append(PageBreak())

    #==============================================================================
    # Summary of reduction parameters
    #==============================================================================

    plotReductionSummary(Story, profile)
    Story.append(PageBreak())
    
    #==============================================================================
    # Image display of the SC flat
    #==============================================================================
    
    plotTitle(Story,"SC FLAT image")
    plotSubtitle(Story,"In ADU, with horizontal wavelength axis (increasing to the right).")
    
    imgdata = io.StringIO()
    plt.clf()
    plt.rc('xtick', labelsize=5)
    plt.rc('ytick', labelsize=5)
    widthfig = 15 * cm
    heightfig= 24 * cm
    figaspect = (1.0*profile.imaging_data_sc.shape[1]/profile.imaging_data_sc.shape[0])*2
    plt.imshow(profile.imaging_data_sc,vmin=np.percentile(profile.imaging_data_sc,1),vmax=np.percentile(profile.imaging_data_sc,99),cmap='cubehelix_r', interpolation='nearest', aspect=figaspect)
    plt.colorbar()
    plt.savefig(imgdata, format='PDF', dpi=250, bbox_inches='tight')
    plt.close('all')
    pi1 = PdfImage(imgdata, width=widthfig, height=heightfig, kind='bound')

    Story.append(pi1)
    Story.append(PageBreak())

    #==============================================================================
    # Image display of the SC extraction profiles
    # Commented out as the reading of the profile tables does not work
    #==============================================================================
#    
#    plotTitle(Story,"SC spectrum extraction profiles")
#    plotSubtitle(Story,"Horizontal wavelength axis (increasing to the right).")
#    
#    imgdata = cStringIO.StringIO()
#    plt.clf()
#    plt.rc('xtick', labelsize=5)
#    plt.rc('ytick', labelsize=5)
#    widthfig = 15 * cm
#    heightfig= 24 * cm
#    figaspect = (1.0*profile.profile_data.shape[1]/profile.profile_data.shape[0])*2
#    plt.imshow(profile.profile_data,vmin=np.percentile(profile.profile_data,1),vmax=np.percentile(profile.profile_data,99),cmap='cubehelix_r', interpolation='nearest', aspect=figaspect)
#    plt.colorbar()
#    plt.savefig(imgdata, format='PDF', dpi=250, bbox_inches='tight')
#    plt.close('all')
#    pi1 = PdfImage(imgdata, width=widthfig, height=heightfig, kind='bound')
#
#    Story.append(pi1)
#    Story.append(PageBreak())
    
    
    #==============================================================================
    # Image display of FT spectra
    #==============================================================================
    
    plotTitle(Story,"FT FLAT image")
    plotSubtitle(Story,"In ADU, with horizontal wavelength axis (increasing to the right). Two polarizations in split mode (channels 0-4 and 5-9).")
    
    imgdata = io.StringIO()
    plt.clf()
    plt.rc('xtick', labelsize=5)
    plt.rc('ytick', labelsize=5)
    widthfig = 15 * cm
    heightfig= 23 * cm
    figaspect = (1.0*profile.imaging_data_ft.shape[0]/profile.imaging_data_ft.shape[1])*2
    plt.imshow(profile.imaging_data_ft.T,vmin=np.percentile(profile.imaging_data_ft,1),vmax=np.percentile(profile.imaging_data_ft,99),cmap='cubehelix', interpolation='nearest', aspect=figaspect)
    plt.colorbar()
    plt.savefig(imgdata, format='PDF', dpi=250, bbox_inches='tight')
    plt.close('all')
    pi2 = PdfImage(imgdata, width=widthfig, height=heightfig, kind='bound')
    
    Story.append(pi2)
    Story.append(PageBreak())

    #==============================================================================
    # Create PDF report from Story
    #==============================================================================
    print("Create the PDF")

    gravi_visual_class.TITLE    = "GRAVITY FLAT Quality Control Report"
    gravi_visual_class.PAGEINFO = "FLAT file: "+filename+".fits"
    reportname = filename+"-FLAT.pdf"
    
    doc = SimpleDocTemplate(reportname)
    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)

    print((" "+reportname)) 


#==============================================================================
# MAIN PROGRAM    
#==============================================================================

if __name__ == '__main__':
    filename='../test-files/GRAVITY.2016-12-17T12-31-58_flat'
    
    if len(sys.argv) == 2 :
        filename=sys.argv[1]
        
    if filename == '' :
        filename=input(" Enter PROFILE file name (without .fits) : ")

    profile = gravi_visual_class.Profile(filename+'.fits')

    produce_profile_report(profile,filename)

