#!/usr/local/bin/python2.7

"""

This script runs on ippc11 once a day at 7:00 HST under the ipp account

"""

import MySQLdb
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import pylab
import math 
import datetime 
import os 

class HeathersPlot:
    """No need for a class here but I'm too lazy to reimplement it
    """

    COLORS = ['#00FF00', '#0033CC', '#FF0000']

    IMAGES_DIRECTORY = "/data/ipp009.0/czartool_plots/heathers_plots"
    CAM_WEB_FILENAME = "/data/ipp009.0/czartool_plots/heathers_plots/cam.png"
    CAM_MERGED_WEB_FILENAME = "/data/ipp009.0/czartool_plots/heathers_plots/cam_merged.png"
    SKYCAL_WEB_FILENAME = "/data/ipp009.0/czartool_plots/heathers_plots/skycal.png"
    SKYCAL_MERGED_WEB_FILENAME = "/data/ipp009.0/czartool_plots/heathers_plots/skycal_merged.png"

    def __init__(self):
        self.db = MySQLdb.connect("ippdb01", "ipp", "ipp", "gpc1")

    CAM_STATEMENT ="""SELECT ra, decl, addRun.state, addProcessedExp.fault 
FROM addRun 
 LEFT JOIN addProcessedExp USING(add_id) 
 JOIN camRun ON stage_id = cam_id 
 JOIN chipRun USING(chip_id) 
 JOIN rawExp USING(exp_id)
WHERE stage = 'cam' and addRun.dvodb = 'LAP.20130717'
"""

    CAM_MERGED_STATEMENT = """SELECT ra, decl, mergedvodbRun.state, mergedvodbProcessed.fault 
FROM mergedvodbRun 
 LEFT JOIN mergedvodbProcessed USING(merge_id)
 LEFT JOIN minidvodbRun USING(minidvodb_id)
 LEFT JOIN addRun USING(minidvodb_name)
 LEFT JOIN addProcessedExp USING(add_id)
 JOIN camRun ON stage_id = cam_id
 JOIN chipRun USING(chip_id)
 JOIN rawExp USING(exp_id)
WHERE stage = 'cam' AND mergedvodbRun.mergedvodb = 'LAP.20130717'
"""

    SKYCAL_STATEMENT = """SELECT radeg*3.1415927/180., decdeg*3.1415927/180., addRun.state, addProcessedExp.fault 
FROM addRun
 LEFT JOIN addProcessedExp USING(add_id)
 JOIN skycalRun ON skycal_id = stage_id
 JOIN skycalResult USING (skycal_id)
 JOIN staticskyInput USING (sky_id, stack_id)
 JOIN staticskyRun USING (sky_id)
 JOIN stackRun USING (stack_id)
 JOIN skycell using (tess_id, skycell_id)
WHERE stage = 'skycal' AND addRun.dvodb = 'LAP.20130717' 
"""

    SKYCAL_MERGED_STATEMENT = """SELECT radeg*3.1415927/180., decdeg*3.1415927/180., mergedvodbRun.state, mergedvodbProcessed.fault
FROM mergedvodbRun
 LEFT JOIN mergedvodbProcessed USING(merge_id)
 LEFT JOIN minidvodbRun USING(minidvodb_id)
 LEFT JOIN addRun USING(minidvodb_name)
 LEFT JOIN addProcessedExp USING(add_id)
 JOIN skycalRun ON skycal_id = stage_id
 JOIN skycalResult USING(skycal_id)
 JOIN staticskyInput USING(sky_id, stack_id)
 JOIN staticskyRun USING (sky_id)
 JOIN stackRun using (stack_id)
 JOIN skycell using (tess_id, skycell_id)
WHERE stage = 'skycal' AND addRun.dvodb = 'LAP.20130717'"""

    def fetch_data(self, statement):
        cursor = self.db.cursor()
        cursor.execute(statement)
        ras = [ ]
        decs = [ ]
        states = [ ]
        for row in cursor.fetchall():
            if row[2] == "full":
                if row[3] == 0:
                    state = 0
                else:
                    state = 2
            else:
                if row[3] is None:
                    state = 1
                else:
                    state = 2
            ras.append(row[0])
            decs.append(row[1])
            states.append(state)
        return (ras, decs, states)

    def plot(self, _ras, _decs, states, stage):
        today = datetime.date.today().isoformat()
        output_filename = '%s/%s.%s.png' % (HeathersPlot.IMAGES_DIRECTORY, stage, today)
        ras = np.array(_ras)
        decs = np.array(_decs)
        colors = [ ]
        for state in states:
            colors.append(HeathersPlot.COLORS[state])
        fig = plt.figure()
        ax = pylab.subplot(111, projection="hammer")
        ax.scatter(math.pi-ras, decs, c = colors, lw=0, s=1)
        ax.set_xlim(0, 2*math.pi)
        ax.set_title("addstar: %s stage - %s" % (stage, today))
        ax.grid(True)
        ax.yaxis.set_ticklabels(['',''])
        ax.xaxis.set_ticklabels(['',''])
        #Heather doesn't like this: ax.xaxis.set_ticklabels(['22h', '20h', '18h','16h','14h','12h','10h','08h','06h','04h','02h'])
        plt.savefig(output_filename, dpi=100, facecolor="white", edgecolor="white")
        return output_filename

    def relink_webfiles(self, web_filename, new_filename):
        print "Have to replace %s by %s" % (web_filename, new_filename)
        try:
            os.unlink(web_filename)
        except OSError, e: # No such file or directory
            print e
        os.symlink(new_filename, web_filename)

    @staticmethod
    def mkdir(dirname):
        try:
            os.makedirs(dirname)
        except OSError, e:
            if str(e).startswith("[Errno 17] File exists"):
                pass
            else:
                raise e

    def update_cam_plot(self):
        HeathersPlot.mkdir(HeathersPlot.IMAGES_DIRECTORY)
        (ras, decs, states) = self.fetch_data(HeathersPlot.CAM_STATEMENT)
        new_filename = self.plot(ras, decs, states, 'Camera')
        self.relink_webfiles(HeathersPlot.CAM_WEB_FILENAME, new_filename)

    def update_cam_merged_plot(self):
        HeathersPlot.mkdir(HeathersPlot.IMAGES_DIRECTORY)
        (ras, decs, states) = self.fetch_data(HeathersPlot.CAM_MERGED_STATEMENT)
        new_filename = self.plot(ras, decs, states, 'Camera_Merged')
        self.relink_webfiles(HeathersPlot.CAM_MERGED_WEB_FILENAME, new_filename)

    def update_skycal_plot(self):
        HeathersPlot.mkdir(HeathersPlot.IMAGES_DIRECTORY)
        (ras, decs, states) = self.fetch_data(HeathersPlot.SKYCAL_STATEMENT)
        new_filename = self.plot(ras, decs, states, 'SkyCal')
        self.relink_webfiles(HeathersPlot.SKYCAL_WEB_FILENAME, new_filename)

    def update_skycal_merged_plot(self):
        HeathersPlot.mkdir(HeathersPlot.IMAGES_DIRECTORY)
        (ras, decs, states) = self.fetch_data(HeathersPlot.SKYCAL_MERGED_STATEMENT)
        new_filename = self.plot(ras, decs, states, 'SkyCal_Merged')
        self.relink_webfiles(HeathersPlot.SKYCAL_MERGED_WEB_FILENAME, new_filename)

if __name__ == "__main__":
    hp = HeathersPlot()
    hp.update_cam_plot()
#    hp.update_skycal_plot()
#    hp.update_cam_merged_plot()
#    hp.update_skycal_merged_plot()

#don't make those for now since we don't do that yet
