#!/usr/bin/env jython

import tempfile
import os
import time

from ipptopsps import IppToPsps

'''
Plot class
'''
class Plot(object):

    '''
    Constructor
    '''
    def __init__(self, logger, skychunk, ippToPspsDb):

        self.logger = logger
        self.skychunk = skychunk 
        self.ippToPspsDb = ippToPspsDb

    '''
    Creates a density plot of pending exposures for this skychunk
    '''
    def createDensityPlot(self, batchType, forCzartool=False):

        tempFilename = "./" + self.skychunk.name + "_" + batchType + "_plotData.dat"
        DATFILE = open(tempFilename,'w')
        max = self.ippToPspsDb.createPendingDensityPlotData(batchType, DATFILE)
        DATFILE.close()

        if max == 0: max = 1

        timestamp = time.strftime('%Y_%m%d_%H%M%S')

        if forCzartool:
            ## XXX from config??
            OUTPUTFILE = self.skychunk.czarPlotsPath + "/ippToPsps_density_" + self.skychunk.name + "_" + batchType + ".png"
        else:
            OUTPUTFILE = self.skychunk.name + "_" + batchType + "_" + timestamp + ".png"

        f = os.popen('/home/panstarrs/ipp/local/bin/gnuplot', 'w')
            
        if 0:
            TERM = "X11"
        else:
            TERM = "png font \"/usr/share/fonts/corefonts/arial.ttf\" 8"
                     
        print >> f, "set term " + TERM + "; \
            set output \"" + OUTPUTFILE + "\"; \
            set title \"Unprocessed " + batchType + " items for '" + self.skychunk.name + "' as of " + timestamp + "\"; \
            set grid; \
            set xrange [" + str(self.skychunk.minRa) + ":" + str(self.skychunk.maxRa) + "] reverse; \
            set yrange [" + str(self.skychunk.minDec) + ":" + str(self.skychunk.maxDec) + "]; \
            unset key; \
            set palette rgb 22,13,10; \
            set ylabel \"Dec\"; \
            set ylabel \"RA\"; \
            set cbrange [0:" + str(max) + "]; \
            set datafile missing \"NaN\"; \
            plot '" + tempFilename + "' using 1:2:3 with image"

        f.flush()
        f.close()
        #os.remove(tempFilename)

