# -*- coding: utf-8 -*-
'''
    Copyright (C) 2020 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 mercantile
from osgeo import ogr
from osgeo import gdal
from osgeo import gdalconst
import tempfile
import os
import shutil
import subprocess
import math

class TileGenerator:
	"""
		- tile_sizes = Array of tile sizes in pixel, which should be rendered
		- zoom_range = Range of zooms, tiles are created for
		- densities = Array with counts of data points per density_base, where tiles are created for
		- density_base = Radios of circle as a datum plane for the densities values
		- nodata_value = Value used for pixels without valid data
	"""
	def __init__(self, tile_sizes = [256, 512], zoom_range = [14, 19], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
		self._tile_sizes = tile_sizes
		self._zoom_range = zoom_range
		self._densities = densities
		self._density_base = density_base
		self._nodata_value = nodata_value
		self._debug = debug
		
		# -999 is a workaround, as long gdal python api does not handle addAlpha
		self._colors = {
			-999: '255 255 255',
			0: '0 0 139',
			2: '30 144 255',
			6: '173 216 230',
			10: '240 248 255'
		}
		
		ogr.UseExceptions()

	def run(self, input_file, output_directory, tile_sizes = None, zoom_range = None, densities = None, density_base = None, nodata_value = None):
		"""
			Runs all nescessary steps to create the tiles.
			All default parameters equal to none are replaced by the one of the object
			input_file = vrt source file used as a base for all steps to creating the tiles
		"""
		if tile_sizes is None:
			tile_sizes = self._tile_sizes
		if zoom_range is None:
			zoom_range = self._zoom_range
		if densities is None:
			densities = self._densities
		if density_base is None:
			density_base = self._density_base
		if nodata_value is None:
			nodata_value = self._nodata_value
		
		# get source boundaries (Envelope / Extent)
		datasource = ogr.Open(input_file)
		if datasource is None:
			raise FileNotFoundError('Could not open input file {}'.format(input_file))
		if datasource.GetLayerCount() < 1:
			raise ReferenceError('No layers in input file') 
		source_layer = datasource.GetLayerByIndex(0)
		source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
		source_layer_name = source_layer.GetName()
		
		# define density information for gridding algorithm
		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(density_base) / math.pi
		radius_x = circle_radius / lon_metre_max
		radius_y = circle_radius / lat_metre_max
		
		for density_min in densities:
			for tile_size in tile_sizes:
				gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
				
				tile_resolution = self._tile_width(tile_size, zoom_range[1])
				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))
				
				if self._debug:
					print("Run for density {} and {} tile size:".format(density_min, tile_size))
					print("  Statistics:")
					print("    Found {} Points".format(source_layer.GetFeatureCount()))
					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 * density_base / lon_metre_max / lat_metre_max))
					print("    Min density per pixel: {}".format(density_min * density_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
					print("    gridding algorithm {}".format(gridding_algorithm))
					
				# create the grid data
				raster_file = self.raster_create(input_file, source_layer_name, target_x_res, target_y_res, gridding_algorithm)
				# hillshade
				hillshade_file = self.hillshade_create(raster_file)
				# color relief
				color_relief_file = self.color_relief_create(raster_file)
				# slopeshade
				slopeshade_file = os.path.join(output_directory, 'water_depth_slopeshade.tif')
				slopeshade_file = self.slopeshade_create(raster_file, slopeshade_file)
				# merge color relief and hillshade
				merged_file = os.path.join(output_directory, 'water_depth_{}_{}.tif'.format(density_min, density_base))
				self.merge_color_relief_hillshade(color_relief_file, hillshade_file, merged_file)
				# create the tiles
				title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(density_min, density_base, tile_size)
				tiles_output = os.path.join(output_directory, '{}_{}/{}'.format(density_min, density_base, tile_size))
				self.tiles_create(merged_file, title, tile_size, tiles_output)

	def raster_create(self, input_file, layers, width, height, gridding_algorithm, nodata_value=None, output_file='/vsimem/water_depth.tif'):
		"""
			Rastering the data from source file into a tif.
			The input should be a vrt source file.
			The function returns the path to the generated tif file.
		"""
		if nodata_value is None:
			nodata_value = self._nodata_value
		
		grid_options = gdal.GridOptions(
			outputType = gdal.GDT_Float32,
			format = "GTiff",
			width = width,
			height = height,
			outputSRS = "WGS84",
			noData = nodata_value,
			layers = layers,
			algorithm = gridding_algorithm
		)
		gdal.Grid(output_file, input_file, options = grid_options)
		return output_file

	def hillshade_create(self, input_file, output_file='/vsimem/water_depth_hillshade.tif'):
		"""
			Creates the hillshade from a raster tif file and returns the path to the resulting tif file
		"""
		gdal.DEMProcessing(output_file, input_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
		return output_file

	def color_relief_create(self, input_file, output_file='/vsimem/water_depth_color_relief.tif', colors = None):
		"""
			Creates the color relief from a raster tif and returns the path to the resulting tif file
		"""
		if colors is None:
			colors = self._colors
		
		gdal_file_color_relief_config = tempfile.NamedTemporaryFile(mode='w', suffix='txt')
		for depth in colors:
			gdal_file_color_relief_config.write("{} {}\n".format(depth, colors[depth]))
		gdal_file_color_relief_config.flush()
		gdal.DEMProcessing(output_file, input_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config.name), addAlpha = True)
		gdal_file_color_relief_config.close()
		return output_file
	
	def slopeshade_create(self, input_file, output_file):
		gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
		gdal_file_slopeshade_config = tempfile.NamedTemporaryFile(mode='w', suffix='txt')
		gdal_file_slopeshade_config.write("0 255 255 255\n")
		gdal_file_slopeshade_config.write("90 0 0 0\n")
		gdal_file_slopeshade_config.write("270 0 0 0\n")
		gdal_file_slopeshade_config.write("360 255 255 255\n")
		gdal_file_slopeshade_config.flush()
		gdal.DEMProcessing(gdal_file_slopeshade_tmp, input_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"), slopeFormat = 'degree', zeroForFlat = True, addAlpha = True)
		gdal.DEMProcessing(output_file, gdal_file_slopeshade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slopeshade_config.name), addAlpha = True)
		gdal_file_slopeshade_config.close()
		return output_file
	
	def merge_color_relief_hillshade(self, input_color_relief_file, input_hillshade_file, output_file):
		# dstNodata is a workaround for not working addAlpha in color-relief
		gdal.Warp(output_file, [input_color_relief_file, input_hillshade_file], options = gdal.WarpOptions(format = 'GTiff', dstAlpha = False, dstNodata = "255 255 255"))
		return output_file

	def tiles_create(self, input_file, title, tile_size, output_directory, zoom_range = None):
		if zoom_range is None:
			zoom_range = self._zoom_range
		
		tile_zoom_option = "-".join(map(str, zoom_range))
		# using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros
		subprocess.run(['gdal2tiles-gnuboat.py', '-q', '-w', 'none', '--tilesize={}'.format(tile_size), '-z', tile_zoom_option, '-t', title, input_file, output_directory], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

	def _tile_width(self, tile_size, zoomlevel):
		lng_lat_box = mercantile.bounds(mercantile.Tile(1, 1, zoomlevel))
		tiles = math.sqrt(self._tile_number(zoomlevel))
		#print ({"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles})
		return {"tile_size": tile_size, "longitude": abs(lng_lat_box.west - lng_lat_box.east), "latitude": abs(lng_lat_box.north - lng_lat_box.south)}

	def _tile_number(self, zoomlevel):
		return 2**(zoomlevel*2)

	#def contours_create():
		# @todo Cut Tifs / warp
		#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(density_min, density_base, 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
		#print("  Created contour lines {}".format(gdal_file_contours))
		
	#def crop():
		# cropping the tifs
		#gdal.Warp('/tmp/gnuboat/test.tif', gdal_file_color_relief, options = gdal.WarpOptions(format = 'GTiff', dstAlpha = True, srcNodata = "255 255 255", dstNodata = target_nodata_value, cutlineDSName = '/tmp/gnuboat/contours/contour-0.shp', cutlineLayer="contour-0", cropToCutline=True))
