# -*- 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
import copy
from pathlib import Path
from PIL import Image

try:
	from dataclasses import dataclass
	
	#@dataclass
	#class TileWidth:
		#"""
			#tile_size: The tile size in Pixel,
			#longitude: The width of the Tile in decimal degrees
			#latitude:  The height of the Tile in decimal degrees
		#"""
		#tile_size: int
		#longitude: float
		#latitude: float
	
	@dataclass
	class ResultPath:
		"""
			path: Absolute path of the created results
			prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
		"""
		path: str
		prefixes: dict
		
except ImportError:
	#class TileWidth:
		#"""
			#Workaround for @dataclass, until python 3.7 is available in main distros
		#"""
		#def __init__(self, tile_size, longitude, latitude):
			#self.tile_size = tile_size
			#self.longitude = longitude
			#self.latitude = latitude
	
	class ResultPath:
		"""
			path: Absolute path of the created results
			prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
		"""
		def __init__(self, path, prefixes):
			self.path = path
			self.prefixes = prefixes

class ZoomRange(dict):
	def __init__(self, minimum, maximum):
		super(ZoomRange, self).__init__({'minimum': minimum, 'maximum': maximum})
		
	def minimum(self):
		return self['minimum']
	
	def maximum(self):
		return self['maximum']
	
	def from_dict(dictionary):
		return ZoomRange(dictionary['minimum'], dictionary['maximum'])

class LngLatBbox(dict):
	def __init__(self, west, south, east, north):
		super(LngLatBbox, self).__init__({'west': west, 'south': south, 'east': east, 'north': north})
		
	def west(self):
		return self['west']
	
	def south(self):
		return self['south']
	
	def east(self):
		return self['east']
	
	def north(self):
		return self['north']
		
	def to_mercantile_bbox(self):
		return mercantile.LngLatBbox(self.west(), self.south(), self.east(), self.north())
	
	def from_mercantile_bbox(mercantile_bbox):
		return LngLatBbox(mercantile_bbox.west, mercantile_bbox.south, mercantile_bbox.east, mercantile_bbox.north)
	
	def from_dict(dictionary):
		if dictionary is None:
			return None
		return LngLatBbox(dictionary['west'], dictionary['south'], dictionary['east'], dictionary['north'])

class RasterSlice(dict):
	"""
		lng_lat_box: LngLatBbox
		zoom_range: ZoomRange
		tile_size: The tile size in Pixel,
		grid_width: The width of the resulting rastr
		grid_height:  The height of the resulting rastr
		
		It's derived from dict to be json serialisable
	"""
	def __init__(self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height):
		super(RasterSlice, self).__init__({'lng_lat_box': lng_lat_box, 'zoom_range': zoom_range, 'tile_size': tile_size, 'grid_width': grid_width, 'grid_height': grid_height})
		
	def lng_lat_bbox(self):
		return self['lng_lat_box']
	
	def zoom_range(self):
		return self['zoom_range']
	
	def tile_size(self):
		return self['tile_size']
	
	def grid_width(self):
		return self['grid_width']
	
	def grid_height(self):
		return self['grid_height']
	
	def from_dict(dictionary):
		if dictionary is None:
			return None
		return RasterSlice(LngLatBbox.from_dict(dictionary['lng_lat_box']), ZoomRange.from_dict(dictionary['zoom_range']), dictionary['tile_size'], dictionary['grid_width'], dictionary['grid_height'])

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], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
		self._tile_sizes = tile_sizes
		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 fit_extent_to_tiles(self, lng_lat_box, zoom_range):
		"""
			Enlarges the extent (given by lng_lat_box) to the borders of the tiles
			lng_lat_box is of Type LngLatBbox
		"""
		tile_bounding = mercantile.bounding_tile(lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(), lng_lat_box.north())
		if tile_bounding.z > zoom_range.minimum():
			return LngLatBbox.from_mercantile_bbox(mercantile.bounds(mercantile.parent(tile_bounding, zoom=zoom_range.minimum())))
		else:
			return LngLatBbox.from_mercantile_bbox(mercantile.bounds(tile_bounding))

	def slices(self, input_file, zoom_range, tile_sizes = None, raster_file_size_max = 1024 * 1024 * 1024 * 8):
		"""
			Slice the complete area of input_file into smaller pieces,
			so that each created raster file is smaller than raster_file_size_max
			and cut into pieces at the borders of tiles and not thorugh tiles.
			It returns an array of latitude longitude boxes representaing the borders, per slice.
		"""
		if tile_sizes is None:
			tile_sizes = self._tile_sizes
		
		datasource = self._datasource_open(input_file)
		source_layer = datasource.GetLayerByIndex(0)
		west, east, south, north = source_layer.GetExtent()
		
		raster_slices = []
		for tile_size in tile_sizes:
			# fitting to tile borders
			lng_lat_box = self.fit_extent_to_tiles(LngLatBbox(west, south, east, north), zoom_range)
			# The lng_lat_box is exactly on the border between tiles. Since there are rounding errors,
			# we move the corner edges a very little bit (about a few mm) into the tile. This makes sure,
			# that we only get those tiles returned, which are really in the lng_lat_box.
			tiles_zoom_min = mercantile.tiles(lng_lat_box.west() + 1*10**-7, lng_lat_box.south() + 1*10**-7, lng_lat_box.east() - 1*10**-7, lng_lat_box.north() - 1*10**-7, zoom_range.minimum())
					
			# calculating size of raster file for GDT_Float32 = 32bits
			delta_zoom = math.floor(math.log(raster_file_size_max / (tile_size**2 * 32)) / math.log(4))
			steps = math.floor((zoom_range.maximum() - zoom_range.minimum()) / delta_zoom)
			zoom_steps = []
			step = zoom_range.minimum()
			while step < zoom_range.maximum():
				zoom_steps.append(step)
				step += delta_zoom + 1
			for tile in tiles_zoom_min:
				raster_slices += self._slice_tile(tile, zoom_steps, zoom_range.maximum(), tile_size, source_layer)
		return raster_slices

	def _slice_tile(self, parent_tile, zoom_steps, zoom_total_max, tile_size, source_layer, tiles_with_geometry = True):
		if len(zoom_steps) < 1:
			raise ValueError('No zoomsteps given to slice tile generation')
		zoom_min = zoom_steps[0]
		if len(zoom_steps) < 2:
			zoom_max = zoom_total_max
		else:
			zoom_max = zoom_steps[1] - 1
		
		raster_slices = []
		lng_lat_box = mercantile.bounds(parent_tile) 
		width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size
		if width != round(width):
			raise ValueError('Found a slice, with incomplete tiles')
		raster_slice = RasterSlice(LngLatBbox.from_mercantile_bbox(lng_lat_box), ZoomRange(zoom_min, zoom_max), tile_size, width, width)
		raster_slices.append(raster_slice)
		if len(zoom_steps) > 1:
			zoom_steps_new = copy.deepcopy(zoom_steps)
			zoom_steps_new.pop(0)
			zoom_min_new = zoom_steps_new[0]
			for child in mercantile.children(parent_tile, zoom=zoom_min_new):
				# test, if tile has geometry
				lng_lat_box = mercantile.bounds(child)
				source_layer.SetSpatialFilterRect(lng_lat_box.west, lng_lat_box.south, lng_lat_box.east, lng_lat_box.north)
				if source_layer.GetNextFeature() or not tiles_with_geometry:
					raster_slices += self._slice_tile(child, zoom_steps_new, zoom_total_max, tile_size, source_layer, tiles_with_geometry = tiles_with_geometry)
				source_layer.SetSpatialFilter(None)
		return raster_slices


	def run(self, input_file, output_directory, tile_slice, 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
			Returns an array of paths with the created tiles if successfull
		"""
		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 = self._datasource_open(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
		
		tile_result_paths = []
		for density_min in densities:
			gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
			if self._debug:
				print("Run for density {} and {} tile size:".format(density_min, tile_slice.tile_size()))
				print("  Statistics:")
				print("    Found {} Points".format(source_layer.GetFeatureCount()))
				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, tile_slice, 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_slice.tile_size())
			prefix_density = '{}_{}'.format(density_min, density_base)
			tiles_output = os.path.join(output_directory, '{}/{}'.format(prefix_density, tile_slice.tile_size()))
			self.tiles_create(merged_file, title, tile_slice.tile_size(), tiles_output, zoom_range = tile_slice.zoom_range())
			tile_result_paths.append(ResultPath(tiles_output, {'tile_size': str(tile_slice.tile_size()), 'density': prefix_density}))
		return tile_result_paths

	def raster_create(self, input_file, layers, tile_slice, 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 = tile_slice.grid_width(),
			height = tile_slice.grid_height(),
			outputSRS = "WGS84",
			outputBounds = [tile_slice.lng_lat_bbox().west(), tile_slice.lng_lat_bbox().north(), tile_slice.lng_lat_bbox().east(), tile_slice.lng_lat_bbox().south()],
			noData = nodata_value,
			layers = layers,
			spatFilter = (tile_slice.lng_lat_bbox().west(), tile_slice.lng_lat_bbox().south(), tile_slice.lng_lat_bbox().east(), tile_slice.lng_lat_bbox().north()), 
			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):
		tile_zoom_option = '{}-{}'.format(zoom_range.minimum(), zoom_range.maximum())
		# 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 move_tiles_in_place(self, source_path, target_path, skip_empty = True):
		"""
			Moves the generated tiles from the source_path into the target_path.
			It moves file per file, so that the tiles are going to be integrated into an existing folder.
			If skip_emtpy = True only one empty tile is copied to the top level directory. All other empty
			tiles are not moved into target_path.
		"""
		copied_empty_tile = False
		
		src_path = Path(source_path)
		trg_path = Path(target_path)
		empty_tile = trg_path.joinpath('empty_tile.png')
		for path in Path(source_path).rglob('*.png'):
			# Substract source_path from path and make it relative to
			# target_path
			relative = path.relative_to(src_path)
			relative_path = trg_path.joinpath(relative)
			if self._tile_is_empty(path) and skip_empty:
				if not copied_empty_tile:
					if not empty_tile.parent.exists():
						os.makedirs(empty_tile.parent)
					shutil.copy(path, empty_tile)
					copied_empty_tile = True
			else:
				if not relative_path.parent.exists():
					os.makedirs(relative_path.parent)
				shutil.copy(path, relative_path)

	def _datasource_open(self, source_file):
		datasource = ogr.Open(source_file)
		if datasource is None:
			raise FileNotFoundError('Could not open input file {}'.format(source_file))
		if datasource.GetLayerCount() < 1:
			raise ReferenceError('No layers in input file') 
		return datasource

	def _tile_is_empty(self, tile_file_path):
		is_empty = True
		colors_tmp = set()
		colors_tmp_transparent = set()
		
		img = Image.open(tile_file_path)
		# calculate histogram for blue channel
		colors_img = img.getcolors(256)
		if not colors_img:
			return False
		else:
			for color in colors_img:
				color_hex = ''.join('{:02X}'.format(value) for value in color[1])
				if color[1][3] != 0:
					return False
		return True

	#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))
