#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    Copyright (C) 2018 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import os
import argparse
import sys
import math
import json
import csv
import xml.etree.ElementTree as ET
from osgeo import ogr
from osgeo import osr
from osgeo import gdal
from osgeo import gdalconst
import shutil

from gnuboat.datahandler import loghandler, logdataset


colors = {
	0: "0 0 139",
	2: "30 144 255",
	6: "173 216 230",
	10: "240 248 255"
}
input_epsg = 'EPSG:4326'
target_nodata_value = 0.0
target_zoomlevel = 19
density_min = 20 # number of points per densitiy_base squaremetres needed to set a value different from nodata
densitiy_base = 100 # squaremetre used as base for density_min

class CsvCallback:
	def __init__(self, output_file):
		self._output_file = output_file
		self._stage = None
		
	def stage_set(self, stage):
		self._stage = stage

	def callback(self, dataset):
		if self._stage is None:
			print("No stage set! Skipping dataset...")
			return
		# only add points with a water depth set
		if dataset.water_depth() is None:
			return
		water_depth = dataset.water_depth() - self._stage
		self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})

def tile_width(zoomlevel):
	tile_size = 256
	tiles = math.sqrt(tile_number(zoomlevel))
	return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}

def tile_number(zoomlevel):
	return 2**(zoomlevel*2)

def main(argv):
	global color, input_epsg, target_nodata_value, target_zoomlevel

	input_file_path = None
	output_directory = None
	statistics = False

	parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
	parser.add_argument('input_file', metavar='input_file_path', type=str,
						help='JSON file with logfiles and correction data to be processed')
	parser.add_argument('output_directory', metavar='output_directory', type=str,
						help='Write the Digital Terrain Model into this directory (output)')
	parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
                        help='Print some statistics of the input and result datasets')
	parser.add_argument('-p', '--points-min', dest='points_min', type=int,
                        help='Print min points per 100 squaremetre', default=10)
	arguments = parser.parse_args(argv)

	if arguments.input_file is None:
		print('ERROR: No input file specified')
		sys.exit(2)
	#elif not os.path.exists(arguments.input_file):
		print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
		sys.exit(3)
	else:
		input_file_path = arguments.input_file
		
	if arguments.output_directory is None:
		print('ERROR: No output file specified')
		sys.exit(2)
	else:
		output_directory = arguments.output_directory
	
	if arguments.statistics is not None:
		statistics = arguments.statistics
		
	if arguments.points_min is not None:
		density_min = arguments.points_min
		
	gdal_file_contours = os.path.join(output_directory, "contours")
	print("Cleaning up / Preparing output directory")
	if os.path.exists(output_directory):
		for root, dirs, files in os.walk(output_directory):
			for f in files:
				os.unlink(os.path.join(root, f))
			for d in dirs:
				shutil.rmtree(os.path.join(root, d))
	else:
		os.makedirs(output_directory)
	if os.path.exists(gdal_file_contours):
		shutil.rmtree(gdal_file_contours)
	

	with open(input_file_path, 'r') as input_file:
		logfiles = json.load(input_file)
	
	source_data_layer = "tmp_corrected_joined_points"
	corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
	try:
		output_file = open(corrected_joined_point_cloud_file_path, 'w')
	except IOError as error:
		print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
		sys.exit(4)
	output_file_csv = None
	fields = ['lon', 'lat', 'water_depth']
	output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
										fieldnames=fields)
	output_file_csv.writeheader()
	csv_callback = CsvCallback(output_file_csv)
	log_handler = loghandler.LogHandler()

	print("Correcting and combining {} log files".format(len(logfiles)))
	for logfile in logfiles:
		stage = logfile["stage"]
		log_file_path = logfile["file"]
		
		# building the log file path
		if not os.path.isabs(log_file_path):
			log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
		# check stage
		try:
			stage = float(stage)
		except ValueError:
			print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
			continue
		# parse, correct and append log file
		csv_callback.stage_set(stage)
		if not log_handler.gnuboat_read(log_file_path, csv_callback.callback):
			sys.exit(5)
		
		print("  {} correct and joined with stage {}".format(log_file_path, stage))
	output_file.close()

	print("Creating output files")
	# create ogr file info
	source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
	try:
		output_file = open(source_xml_file, 'wb')
	except IOError as error:
		print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
		sys.exit(4)
	xml_data_source = ET.Element("OGRVRTDataSource")
	xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
	xml_source = ET.SubElement(xml_layer, "SrcDataSource")
	xml_source.text = corrected_joined_point_cloud_file_path
	xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
	xml_geometry_type.text = "wkbPoint"
	xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
	xml_layer_system.text = input_epsg
	xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
	xml_tree = ET.ElementTree(xml_data_source)
	xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
	output_file.close()

	# processing data with gdal
	ogr.UseExceptions()
	source_data = ogr.Open(source_xml_file)
	source_layer = source_data.GetLayer(source_data_layer)
	source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
		
	# create the grid data
	gdal_file = "/vsimem/water_depth.tif"
	tile_resolution = tile_width(target_zoomlevel)
	target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
	target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
	
	lon_metre_max = 60 * 1852 * math.cos(math.radians(min(source_y_min, source_y_max))) # metre / degree
	lat_metre_max = 111694 # metre / degree
	
	circle_radius = math.sqrt(densitiy_base) / math.pi
	radius_x = circle_radius / lon_metre_max
	radius_y = circle_radius / lat_metre_max
	gridding_algorithm = "average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}".format(radius_x, radius_y, density_min, target_nodata_value)
	
	if statistics:
		print("Source statistics:")
		print("  source EPSG: {}".format(input_epsg))
		print("  extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
		degree_per_pixel_lon = tile_resolution["longitude"] / tile_resolution["tile_size"]
		degree_per_pixel_lat = tile_resolution["latitude"] / tile_resolution["tile_size"]
		print("  degree / pixel x and y: {}, {}".format(degree_per_pixel_lon, degree_per_pixel_lat))
		print("  metre / pixel x and y: {}, {}".format(degree_per_pixel_lon * lon_metre_max, degree_per_pixel_lat * lat_metre_max))
		print("  Min density per squaredegree: {}".format(density_min * densitiy_base / lon_metre_max / lat_metre_max))
		print("  Min density per pixel: {}".format(density_min * densitiy_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
		print("  gridding algorithm {}".format(gridding_algorithm))
	
	grid_options = gdal.GridOptions(
		outputType = gdal.GDT_Float32,
		format = "GTiff",
		width = target_x_res,
		height = target_y_res,
		outputSRS = "WGS84",
		noData = target_nodata_value,
		layers = source_data_layer,
		#algorithm = "invdist:power=2.0:smoothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata={}".format(target_nodata_value)
		algorithm = gridding_algorithm
	)
	gdal.Grid(gdal_file, source_xml_file, options = grid_options)
	print("  Created raster DEM in memory")
	
	# hillshade
	gdal_file_hillshade  = os.path.join(output_directory, "water_depth_hillshade.tif")
	gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
	print("  Created hillshade in {}".format(gdal_file_hillshade))
	
	# color relief
	gdal_file_color_relief = os.path.join(output_directory, "water_depth_color_relief.tif")
	gdal_file_color_relief_config = os.path.join(output_directory, "tmp_water_depth_color_relief_config.txt")
	with open(gdal_file_color_relief_config, 'w') as color_config:
		for depth in colors:
			color_config.write("{} {}\n".format(depth, colors[depth]))
	gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config))
	print("  Created color relief in {}".format(gdal_file_color_relief))
	
	# slope shade
	gdal_file_slope_shade_tmp = "/vsimem/tmp_water_depth_slope_shade.tif"
	gdal_file_slope_shade = os.path.join(output_directory, "water_depth_slope_shade.tif")
	gdal_file_slope_shade_config = os.path.join(output_directory, "tmp_water_depth_slope_shade_config.txt")
	with open(gdal_file_slope_shade_config, 'w') as shade_config:
		shade_config.write("0 255 255 255\n")
		shade_config.write("90 0 0 0\n")
	gdal.DEMProcessing(gdal_file_slope_shade_tmp, gdal_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"))
	gdal.DEMProcessing(gdal_file_slope_shade, gdal_file_slope_shade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slope_shade_config))
	print("  Created slope shade in {}".format(gdal_file_slope_shade))
	
	
	# generate contour lines
	contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
	contour_input_band = contour_input.GetRasterBand(1)
	#Generate layer to save Contourlines in
	contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
	proj = osr.SpatialReference()
	proj.SetWellKnownGeogCS(input_epsg)
	for depth in colors:
		contour_layer = contour_output.CreateLayer('contour-{}'.format(depth), srs = proj)
		field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
		contour_layer.CreateField(field_definition)
		field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
		contour_layer.CreateField(field_definition)
		#Generate Contourlines
		gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
	contour_output = None
	del contour_output

	sys.exit(0)

if __name__ == "__main__":
	main(sys.argv[1:])
