#!/usr/bin/env python
# -*- coding: UTF-8  -*-

import cgi, json
import os, sys
import re
import tempfile, shutil

# enable debugging
#import cgitb
#cgitb.enable()

from ecohydrolib.context import Context
from ecohydrolib.nhdplus2.networkanalysis import getCatchmentFeaturesForGage
from ecohydrolib.spatialdata.utils import OGR_GEOJSON_DRIVER_NAME

CONFIG_FILE = os.path.join( os.environ['DOCUMENT_ROOT'], 'ecohydro.cfg' )
PROJECT_DIR = '/tmp'

CONTENT_TYPE = 'application/json'
CONTENT_TYPE_ERROR = 'text/plain'
RESPONSE_OK = 'OK'

BUFF_LEN = 4096 * 10

context = Context(PROJECT_DIR, CONFIG_FILE) 

if not context.config.has_option('NHDPLUS2', 'PATH_OF_NHDPLUS2_DB'):
    sys.exit("LocateStreamfowGage.py: Config file %s does not define option %s in section %s\n" & \
          (CONFIG_FILE, 'NHDPLUS2', 'PATH_OF_NHDPLUS2_DB'))

if not context.config.has_option('NHDPLUS2', 'PATH_OF_NHDPLUS2_GAGELOC'):
    sys.exit("LocateStreamfowGage.py: Config file %s does not define option %s in section %s\n" & \
          (CONFIG_FILE, 'NHDPLUS2', 'PATH_OF_NHDPLUS2_GAGELOC'))

response = {}

error = False
params = cgi.FieldStorage()
try:
    reachcode = params['reachcode'].value
    if not re.match('^[0-9]+$', reachcode):
        response['message'] = "Illegal reachcode '%s'" % (reachcode,)
        error = True
except KeyError:
    response['message'] = "You must specify a 'reachcode' parameter."
    error = True

try:
    measure = params['measure'].value
    measure = float(measure)
except KeyError:
    response['message'] = "You must specify a 'measure' parameter."
    error = True
except ValueError:
    response['message'] = "Illegal measure '%s'" % (measure,)
    error = True

tmpdir = tempfile.mkdtemp()
featureFilename = getCatchmentFeaturesForGage(context.config, tmpdir, 'catchment', 
                            reachcode, measure,
                            format=OGR_GEOJSON_DRIVER_NAME)
featureFilepath = os.path.join(tmpdir, featureFilename)
if not os.path.isfile(featureFilepath) or not os.access(featureFilepath, os.R_OK):
    response['message'] = "Server error opening feature file"
    error = True

# Write output (error or features)
if error:
    sys.stdout.write( "Content-Type: %s;charset=utf-8\n\n" % (CONTENT_TYPE_ERROR,) )
    sys.stdout.write( response["message"] )
    sys.stdout.write( '\n\n' )

else:
    sys.stdout.write( "Content-Type: %s;charset=utf-8\n\n" % (CONTENT_TYPE,) )
    # Attempt to read features and write them to the response as GeoJSON
    catchment = open(featureFilepath, 'rb')
    data = catchment.read(BUFF_LEN)
    if data:
        while data:
            sys.stdout.write(data)
            data = catchment.read(BUFF_LEN)
    else:
        response['message'] = "Features contained no data"
        json.dump(response, sys.stdout, separators=(',',':') )
    
    catchment.close()
# Clean up
shutil.rmtree(tmpdir)
