#!/usr/local/env python

# 2015-05-01 -- cwaigl@alaska.edu (Chris Waigl)
# Fire detection: GINA download and sync script

from __future__ import print_function, unicode_literals, division
import os
import sys
import argparse
import datetime as dt
import glob
import seaborn as sns
from pygaarst import raster
from pygaarst import basemaputils as bu
from pygaarst.rasterhelpers import PygaarstRasterError
from matplotlib import pyplot as plt
import fiona
from shapely.geometry import Polygon
from shapely.geos import TopologicalError
from descartes import PolygonPatch
from pprint import pprint

sys.path.append(os.path.join(
    os.path.expanduser('~'),
    "Dropbox/Research/satelliteremotesensing/firedetection"))
import viirstools as vt

NASPATH = "/Volumes/cwdata1/VIIRS/GINA/dds.gina.alaska.edu/NPP/viirs"
VIZDIR = "visual"
TESTDIR = "testviz"
SCENELIST = "GINA_list.txt"
FILEPAT = 'SVM12_npp_*.h5'
VF = 'BorealAKForUAFSmoke.json'
VECTOROVERLAY = None            # ugly
if VF:
    VECTOROVERLAY = os.path.join(
        os.path.split(
            os.path.realpath(__file__))[0], VF)
MINFRAC = 0.01   # minimum fractional area for keeping a sub-scene


def printOpenFiles(openfiles):
    print("### %d OPEN FILES:" % (len(openfiles), ))
    pprint([f.x for f in openfiles])


def parse_arguments():
    """Parse arguments"""
    parser = argparse.ArgumentParser(
        description='Produce visualizations of extent of scenes')
    parser.add_argument(
        '-o', dest='overwrt',
        help='overwrite existing images',
        action='store_true')
    parser.add_argument(
        '--testdir',
        help='use a single directory to test')
    parser.add_argument(
        '--ov', dest='overlayvector',
        help="overlay vector file",
        default=VECTOROVERLAY)
    parser.add_argument(
        '--dir', dest='archivedir',
        help="directory containing file archive",
        default=NASPATH)
    parser.add_argument(
        '--num', action='store_true',
        help="print numbers on plot")
    parser.add_argument(
        '--debug', action='store_true',
        help="debug mode")
    return parser.parse_args()


def read_items(filepath):
    """Turns a plain text file file with one item/line into an iterator"""
    with open(filepath, "rU") as src:
        for line in src:
            yield line.strip()


def generate_viz(
    scene, outdir,fig, mm,
    numbers=False,
    debug=False,
    datadir=None,
    overwrite=False):
    if debug:
        import __builtin__
        openfiles = set()
        oldfile = __builtin__.file
        class newfile(oldfile):
            def __init__(self, *args):
                self.x = args[0]
                print("### OPENING %s ###" % str(self.x) )
                oldfile.__init__(self, *args)
                openfiles.add(self)

            def close(self):
                print("### CLOSING %s ###" % str(self.x))
                oldfile.close(self)
                openfiles.remove(self)
        oldopen = __builtin__.open
        def newopen(*args):
            return newfile(*args)
        __builtin__.file = newfile
        __builtin__.open = newopen

    figname = os.path.split('{}_plot.png'.format(scene))[-1]
    if os.path.exists(os.path.join(outdir, figname)): 
        if overwrite:
            print("{} exists, overwriting.".format(figname))
        else:
            print("{} exists, skipping.".format(figname))
            return
    ax = fig.gca()
    if not datadir:
        datadir = os.path.join(NASPATH, scene, 'sdr')
    elif os.path.exists(os.path.join(datadir, scene, 'sdr')):
        datadir = os.path.join(datadir, scene, 'sdr')
    else:
        datadir = os.path.join(datadir, scene)
    print("Working on data in {}.".format(datadir))
    if not os.path.isdir(datadir):
        print("{} is not a directory, skipping.".format(datadir))
        return
    os.chdir(datadir)
    testfiles = glob.glob(FILEPAT)
    print("Working with {} data files.".format(len(testfiles)))
    testfiles.sort()
    current_palette = sns.husl_palette(n_colors=len(testfiles), h=.2, l=.4, s=.9)
    totalfrac = 0.0
    plotobj = []
    plottexts = []
    for idx, tf in enumerate(testfiles):
        print('{}: {}'.format(idx, tf))