#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
    Copyright (C) 2018 - 2020 EngSaS - 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 pathlib
import argparse
import sys
import math
import json
import csv
import xml.etree.ElementTree as ET
import tempfile
from osgeo import ogr
from osgeo import osr
from osgeo import gdal
from osgeo import gdalconst
import shutil
import progressbar
from time import process_time

from gnuboat_common.datahandler import loghandler, logdataset
from gnuboat_common.spatial import tilegenerator

# -999 is a workaround, as long gdal python api does not handle addAlpha
colors = {
    -999: "255 255 255",
    0: "0 0 139",
    2: "30 144 255",
    6: "173 216 230",
    10: "240 248 255"
}
input_epsg = 'EPSG:4326'
target_nodata_value = -999.0
target_zoomlevel = 19
density_min = 10  # number of points per density_base squaremetres needed to set a value different from nodata
density_base = 100  # squaremetre used as base for density_min


class CsvCallback:
    def __init__(self, output_file):
        self._output_file = output_file
        self._stage = None
        self._resultsets = 0

    def count(self):
        return self._resultsets

    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
        })
        self._resultsets += 1


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, density_min, density_base

    input_file_path = None
    output_directory = None
    statistics = False
    tile_sizes = [256]
    skip_empty = True

    gdal.UseExceptions()

    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(
        '-v',
        '--verbose',
        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,
        default=density_min,
        help=
        'Minimum points per {} squaremetre is needed to create a valid depth information'
        .format(density_base)
    )
    parser.add_argument(
        '-z',
        '--zoomlevels',
        dest='zoom_range',
        nargs=2,
        default=[10, 19],
        type=int,
        help='Creates tiles for the specified range of zoomlevels'
    )
    parser.add_argument(
        '--high-res',
        dest='high_res',
        action='store_true',
        help=
        'Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles'
    )
    parser.add_argument(
        '-m',
        '--raster_file_max',
        dest='raster_file_size_max',
        default=1024,
        type=int,
        help='Maximum size of temporary raster Tifs for tile generation in MB'
    )
    parser.add_argument(
        '-k',
        '--keep-empty',
        dest='skip_empty',
        action='store_false',
        help=
        'Do not skip empty tiles (=move only one empty tile into place), when moving tiles into target directory'
    )
    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

    if arguments.zoom_range is not None:
        zoom_range = arguments.zoom_range

    if arguments.high_res is not None and arguments.high_res:
        tile_sizes.append(512)

    if arguments.raster_file_size_max is not None:
        raster_file_size_max = arguments.raster_file_size_max

    if arguments.skip_empty is not None and not arguments.skip_empty:
        skip_empty = arguments.skip_empty

    # create temporary directory
    temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser')

    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(
        temp_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:
        gaugeHeight = logfile["gaugeHeight"]
        referenceWaterLevelGaugeHeight = logfile[
            "referenceWaterLevelGaugeHeight"]
        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:
            gaugeHeight = float(gaugeHeight)
        except ValueError:
            print(
                "gaugeHeight is not convertible into float for file {}. Skipping the file"
                .format(log_file_path)
            )
            continue
        try:
            referenceWaterLevelGaugeHeight = float(
                referenceWaterLevelGaugeHeight
            )
        except ValueError:
            print(
                "referenceWaterLevelGaugeHeight is not convertible into float for file {}. Skipping the file"
                .format(log_file_path)
            )
            continue
        # parse, correct and append log file
        difference = referenceWaterLevelGaugeHeight - gaugeHeight
        csv_callback.stage_set(difference)
        result = log_handler.gnuboat_read_file(
            log_file_path, csv_callback.callback
        )
        if result.messages():
            print('\n'.join(result.errors()))
        if not result.success():
            sys.exit(5)

        print(
            "  {} correct and joined with difference {:.3f}m".format(
                log_file_path, difference
            )
        )
    output_file.close()
    print('  Processed {} points'.format(csv_callback.count()))

    # create ogr file info
    source_xml_file = os.path.join(
        temp_directory, '{}.vrt'.format(source_data_layer)
    )
    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", {'relativeToVRT': "1"}
    )
    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()

    # create csvt file
    try:
        output_file_csvt = open(
            os.path.join(temp_directory, '{}.csvt'.format(source_data_layer)),
            'w'
        )
    except IOError as error:
        print(
            'ERROR: Could not open the output file for the ogr data source description: {}'
            .format(error)
        )
        sys.exit(6)
    output_file_csvt.write('"Real","Real","Real"')
    output_file_csvt.close()

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

    # get source boundaries (Envelope / Extent)
    datasource = ogr.Open(source_xml_file)
    if datasource is None:
        raise FileNotFoundError(
            'Could not open input file {}'.format(source_xml_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(
    )

    tilegen = tilegenerator.TileGenerator(
        tile_sizes=tile_sizes,
        densities=[density_min],
        density_base=density_base,
        debug=statistics
    )
    slices = tilegen.slices(
        source_xml_file,
        tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]),
        raster_file_size_max=raster_file_size_max * 1024 * 1024 * 8
    )
    slices_count = len(slices)
    print('Generated {} slices for rastering'.format(slices_count))

    t1_start = process_time()
    print('Rastering slices and generating tiles')
    with progressbar.ProgressBar(
        max_value=slices_count, redirect_stdout=True
    ) as bar:
        i = 1
        for tile_slice in slices:
            if statistics:
                print(
                    ' Generating tiles for slice {} in {}'.format(
                        i, temp_directory
                    )
                )
            result_paths = tilegen.run(
                source_xml_file, temp_directory, tile_slice
            )
            for path in result_paths:
                tilegen.move_tiles_in_place(
                    path.path,
                    os.path.join(
                        output_directory, path.prefixes['density'],
                        path.prefixes['tile_size']
                    ),
                    skip_empty=skip_empty
                )
            bar.update(i)
            i += 1
    t1_stop = process_time()
    print('  Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60))

    # delete temporary directory
    shutil.rmtree(temp_directory)

    print('Generated tiles in {}'.format(output_directory))

    sys.exit(0)


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