from flask import Flask, render_template, url_for, jsonify, request, send_from_directory, abort
import track_run
import datetime
import json
import zipfile
import os, shutil
from track_plotting import plotting
from track_datasheet import datasheet

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

app = Flask(__name__)

with app.test_request_context():
	url_for('static', filename='css/bootstrap.min.css')
	url_for('static', filename='css/app.css')
	
	url_for('static', filename='javascript/action/drifter.js')
	url_for('static', filename='javascript/action/trajectory.js')
	
	url_for('static', filename='javascript/dispatcher/dispatcher.js')

	url_for('static', filename='javascript/emitter/render.js')

	url_for('static', filename='javascript/lib/require-2.3.2.min.js')
	url_for('static', filename='javascript/lib/jquery-3.1.1.min.js')
	url_for('static', filename='javascript/lib/vue.min.js')
	
	url_for('static', filename='javascript/model/drifter.js')
	url_for('static', filename='javascript/model/trajectory.js')
	
	url_for('static', filename='javascript/store/drifter.js')
	url_for('static', filename='javascript/store/trajectory.js')

	url_for('static', filename='javascript/view/map.js')
	url_for('static', filename='javascript/view/drifter-list.js')
	url_for('static', filename='javascript/view/form.js')
	url_for('static', filename='javascript/view/header.js')
	url_for('static', filename='javascript/view/method-radio.js')
	url_for('static', filename='javascript/view/start-time-calendar.js')
	url_for('static', filename='javascript/view/submit-buttons.js')

	url_for('static', filename='javascript/const/constant.js')
	
	url_for('static', filename='javascript/app.js')

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route('/')
def hello_world():
	# return render_template('index.html')
	return send_from_directory('templates', filename='index.html')

@app.route('/trajectories/')
def calculate_trajectories():
	try:
		lat = float(request.args.get('lat', ''))
		lon = float(request.args.get('lon', ''))
		track_way = request.args.get('trackWay', '')
		track_method = request.args.get('trackMethod', '')
		dataset = request.args.get('dataset', '')
		start = int(request.args.get('start'))
		end = int(request.args.get('end'))
		archive_path = request.args.get('archive')
		h = float(request.args.get('depth'))
		r = float(request.args.get('radius'))
		o = track_run.cal_trajectory(lat,lon, track_way, track_method, dataset, start, end, archive_path, h, r, False, 'idwutm')
		return jsonify(o)
	except Exception as err:
		raise InvalidUsage(err.message, status_code=500)
		# abort(500)

@app.route('/download/', methods=['POST'])
def download_data():
	try:
		__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
		results_dir = os.path.join(__location__, 'Results/')
		for the_file in os.listdir(results_dir):
			file_path = os.path.join(results_dir, the_file)
			try:
				if os.path.isfile(file_path):
					os.unlink(file_path)
			except Exception as e:
					print 'remove results file fail'
		request.get_data()
		trajectories = json.loads(request.data)['data']
		# plotting
		plotting(trajectories, results_dir)
		# csv
		datasheet(trajectories, results_dir)
		# zip
		zf = zipfile.ZipFile(results_dir+'output.zip', mode='w', compression = zipfile.ZIP_DEFLATED)
		try:
			zf.write(results_dir+'output.png', 'output.png')
			zf.write(results_dir+'output.csv', 'output.csv')
		finally:
			zf.close()
		return send_from_directory('Results', filename='output.zip')

	except Exception as err:
		raise InvalidUsage('export data fail', status_code=500)

if __name__ == '__main__':
	# app.debug = True
	#app.run(host='0.0.0.0')
	app.run()