#!/bin/env python

import argparse
import glob
import os
import re
import sys
import yaml
import zipfile

sys.path.append('/home/gis/utils/map-builder/modules/')

import Console
import FileSystem

from Site import Site

cliParser = argparse.ArgumentParser()
cliParser.add_argument('site_path', metavar='SITE_PATH', type=str, help='Path to site data.')
cliParser.add_argument('--verbose', dest='verbose', action='store_true', default=False, help='Turns on INFO and WARNING messages.')
cliParser.add_argument('--wfo', dest='wfo', action='store', default=None, help='Specifies wfo of the site')
cliParser.add_argument('--dl-base', dest='downloadsBaseDir', action='store', default='/home/inundation-resources/downloads', help='Specifies where the inundation downloads base directory is located.')
runtime_config = cliParser.parse_args()

if runtime_config.verbose:
    Console.VERBOSE = True

site = Site.Open(runtime_config.site_path)

if runtime_config.wfo is None:
    Console.info('WFO was not provided. Trying to detect wfo')

    confFile = '{}/geoinfo.yaml'.format(site.GetRootPath())

    if not os.path.exists(confFile):
        Console.error('Config file could not be found while attempting to detect wfo.')
        sys.exit(2)

    fp = open(confFile, 'r')
    conf = yaml.load(fp.read())

    if 'wfo' not in conf:
        Console.info("Config file did not contain the site's wfo. Failed to detect wfo")
        sys.exit(3)

    runtime_config.wfo = conf['wfo']

    Console.info("Detected wfo to be {}".format(runtime_config.wfo))

runtime_config.downloadsBaseDir = os.path.abspath(runtime_config.downloadsBaseDir)

if not os.path.exists(runtime_config.downloadsBaseDir):
    Console.error('Downloads base directory does not exist. Currently set to `{}`'.format(runtime_config.downloadsBaseDir))
    sys.exit(3)

zipDestination = '{0}/{1}/{2}/shapefile/{2}_shapefiles.zip'.format(runtime_config.downloadsBaseDir, runtime_config.wfo, site.GetName())

if not os.path.exists(os.path.dirname(zipDestination)):
    os.makedirs(os.path.dirname(zipDestination))

if os.path.exists(zipDestination):
    Console.info('The zipfile already exists. Overwriting {}'.format(zipDestination))
    os.remove(zipDestination)

zf = zipfile.ZipFile(zipDestination, 'w', zipfile.ZIP_DEFLATED, True)

Console.log("Created {}".format(zipDestination))

for f in FileSystem.find(site.GetRootPath(), nodeType=FileSystem.FILE, exclude=('*.yaml', '.*', 'trash', 'revision.txt')):
    zipPath = f.replace('{}/'.format(site.GetRootPath()), '')

    Console.log("Adding {} at {}".format(f, zipPath))

    zf.write(f, zipPath)

zf.close()

Console.log("Finished writing {}".format(zipDestination))
