#! /bin/env python

import os
import sys

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-e", "--echo", action="store_true", dest="justecho",
                  default=False,
                  help="Echo commands but do not execute them.")
parser.add_option("", "--hours", action="store", dest="hours",
                  default=os.environ.get("PLOT_HOURS", None),
                  help="Space-separated list of plot hours in increasing order, or else the PLOT_HOURS environment variable from the project configuration.")

(options, args) = parser.parse_args()

zplotdargs=args
hours=[]
if not options.hours:
    print("PLOT_HOURS must be defined or specified on command line.")
    sys.exit(1)

print("Plot hours: %s" % options.hours)
hours = [ int(i) for i in options.hours.split() ]

# We have to assume we're never getting more data than for the last
# four hours, so we only want to plot the time periods which overlap
# with that window, at most 2 plot periods.

import time
from datetime import datetime

def formatTime(timet, format="%Y-%m-%d,%H:%M:%S"):
    return datetime.utcfromtimestamp(timet).strftime(format)

currenttime = time.time()
currentday = currenttime - (currenttime % (24*3600))
datatime = currenttime - 4*3600
print("Data time window: %s - %s" % (formatTime(datatime),
                                     formatTime(currenttime)))

# For each plot hour and the plot period it specifies, see if it
# overlaps with the data window.

lasthour = hours[-1]
plotperiods = []
lasttime = None
for d in [ currentday-24*3600, currentday, currentday+24*3600 ]:
    for h in hours:

        if not lasttime:
            lasttime = d + (hours[-1]*3600) - 24*3600
        plottime = d + (h * 3600)
        # print("Checking plot period %s - %s" %
        #    (formatTime(lasttime), formatTime(plottime)))
        if ((lasttime <= datatime and datatime <= plottime) or
            (lasttime <= currenttime and currenttime <= plottime)):
            print("Selecting plot time %s" % formatTime(plottime))
            plotperiods.append(plottime)
        lasttime = plottime


# Any reason this can't be run in parallel?  Leaving serial for now...
for p in plotperiods:
    cmd="zplotd -period " + formatTime(p, "%d-%h-%Y,%H:00:00")
    cmd += " " + " ".join(zplotdargs)
    print(cmd)
    if not options.justecho:
        os.system(cmd)
