#!/usr/bin/env jython

import tempfile
import os
import time

from ipptopsps import IppToPsps

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

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

        self.logger = logger
        self.config = config 
        self.ippToPspsDb = ippToPspsDb

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

        tempFilename = "./" + self.config.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:
            OUTPUTFILE = self.config.czarPlotsPath + "/ippToPsps_density_" + self.config.name + "_" + batchType + ".png"
        else:
            OUTPUTFILE = self.config.name + "_" + batchType + "_" + timestamp + ".png"

        f = os.popen('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.config.name + "' as of " + timestamp + "\"; \
            set grid; \
            set xrange [" + str(self.config.minRa) + ":" + str(self.config.maxRa) + "] reverse; \
            set yrange [" + str(self.config.minDec) + ":" + str(self.config.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)

