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

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

import sys
import numpy as np
import matplotlib.pyplot as plt
from . import gravi_visual_class

#==============================================================================
# Preparation of the report using reportlab
#==============================================================================
def produce_badpix_report(badpix,filename):
    # From gravi_visual_class
    from . import gravi_visual_class
    from .gravi_visual_class import 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, BytesIO
    from svglib.svglib import svg2rlg
    
    #==============================================================================
    # Start Story
    #==============================================================================
    
    Story = [Spacer(1,1*mm)]
    plotSummary (Story, filename, badpix, onTarget=False)
    Story.append(Spacer(1,1*cm))
    
    #==============================================================================
    # Statistics of the bad pixel maps
    #==============================================================================

    plotTitle(Story,"Statistics")
    Story.append(Spacer(1,2*mm))
    
    badpix_number_sc = np.sum(badpix.badpiximage_sc)
    badpix_number_ft = np.sum(badpix.badpixtable_ft)
    keywords = ["Number of SC bad pixels:",
                "Fraction of bad pixels in SC:",
                "Number of FT bad pixels:",
                "Fraction of bad pixels in SC:"
                ]
    keyvals  = [int(badpix_number_sc),
                "%.4f" % (1.0*badpix_number_sc/(badpix.ncol_sc*badpix.nrow_sc)*100.)+' %',
                int(badpix_number_ft),
                "%.4f" % (1.0*badpix_number_ft/(badpix.nregion_ft*badpix.nwave_ft)*100.)+' %'
                ]
    #print badpix_number_sc, badpix.ncol_sc, badpix.nrow_sc
    # Example of conditional coloring
    maxbadpix = 10000 # Limit of acceptable bad pixel number
    if(badpix_number_sc>maxbadpix):
        color_badpixsc = colors.red
    else:
        color_badpixsc = colors.white
    hsize = [8*cm, 3*cm]
    vsize = 8*mm
    textmatrix = list(zip(keywords,keyvals))
    t = Table(textmatrix,colWidths=hsize,rowHeights=vsize)
    t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                           ('BACKGROUND',(0,0),(0,0),color_badpixsc),
                           ('BOX', (0,0), (-1,-1), 2, colors.black),]))

    Story.append(t)
    Story.append(PageBreak())

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

    plotReductionSummary(Story, badpix)
    Story.append(PageBreak())
    
    #==============================================================================
    # Image display of the SC badpix
    #==============================================================================
    
    specres = badpix.header['HIERARCH ESO INS SPEC RES']
    if specres == 'LOW' or specres == 'MEDIUM':
        plotTitle(Story,"SC bad pixel image, dispersion = horizontal")
    else:
        plotTitle(Story,"SC bad pixel image, dispersion = vertical")

    plotSubtitle(Story,"0=good, 1=bad flux on dark, 8=bad rms of dark, 9=both")
    
    cmap = plt.cm.get_cmap('gist_yarg', 9)    #  discrete colors
    
    fig=plt.figure(figsize=(5,8))
    plt.rc('xtick', labelsize=5)
    plt.rc('ytick', labelsize=5)
    if specres == 'LOW' or specres == 'MEDIUM':
        figaspect = (1.0*badpix.badpiximage_sc.shape[1]/badpix.badpiximage_sc.shape[0])*2.0
        plt.imshow(badpix.badpiximage_sc,vmin=0,vmax=9,cmap=cmap, interpolation='nearest', aspect=figaspect)
    else: # HIGH resolution, the spectrum is rotated by 90 deg
        figaspect = (1.0*badpix.badpiximage_sc.shape[0]/badpix.badpiximage_sc.shape[1])*2.0
        plt.imshow(badpix.badpiximage_sc.T,vmin=0,vmax=9,cmap=cmap, interpolation='nearest', aspect=figaspect)
    plt.colorbar()

    # plt.savefig(imgdata, format='PDF', dpi=250, bbox_inches='tight')
    # widthfig = 15 * cm
    # heightfig= 22 * cm
    # pi1 = PdfImage(imgdata, width=widthfig, height=heightfig, kind='bound')
    # Story.append(pi1)

    imgdata = BytesIO()
    fig.savefig(imgdata, format='svg', bbox_inches='tight')
    imgdata.seek(0)  # rewind the data
    drawing = svg2rlg(imgdata)
    Story.append(drawing)

    Story.append(PageBreak())
    
    #==============================================================================
    # Image display of the FT badpix map
    #==============================================================================
    
    plotTitle(Story,"FT bad pixel image (black=bad)")
       
    fig=plt.figure(figsize=(5,8))
    figaspect = (1.0*badpix.badpixtable_ft.shape[1]/badpix.badpixtable_ft.shape[0])*2.0
    plt.imshow(badpix.badpixtable_ft,vmin=0,vmax=1,cmap='gray_r', interpolation='nearest', aspect=figaspect)

    imgdata = BytesIO()
    fig.savefig(imgdata, format='svg', bbox_inches='tight')
    imgdata.seek(0)  # rewind the data
    drawing = svg2rlg(imgdata)
    Story.append(drawing)

    Story.append(Spacer(1,5*mm))

    plt.close('all')

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

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

    print((" "+reportname)) 

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

if __name__ == '__main__':

    filename = '/Users/kervella/Pipelines/GRAVITY.2016-03-18T04-58-51_badpix'

    #filename = 'gravi_bad_map'
    if len(sys.argv) == 2 :
        filename=sys.argv[1]
    if filename == '' :
            filename=input(" Enter bad pixel file name (without .fits) : ")
    
    # File name of the report
    badpix = gravi_visual_class.Badpix(filename+'.fits')
    
    produce_badpix_report(badpix,filename)

