# -*- coding: utf-8 -*-
"""
/***************************************************************************
 PluginDatasetCreateDialog
 This plugin connects to the NDFF api
                              -------------------
        begin                : 2021-12-20
        git sha              : $Format:%H$
        copyright            : (C) 2021 by Zuidt
        email                : richard@zuidt.nl
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
import logging
import os

from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import (
    QDialog,
    QMessageBox,
)
from qgis._core import QgsFeature
from qgis.core import (
    QgsMapLayerProxyModel,
)

from .ext.ndff.api.object import (
    NdffObservation,
    NdffDataset,
)
from .ext.ndff.connector.connector import (
    NdffConnector,
)

from . import LOGGER_NAME

log = logging.getLogger(LOGGER_NAME)

# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'ndffc_plugin_dataset_create_dialog_base.ui'))

PLUGIN_DIALOGS_TITLE = 'NDFF Connector Plugin'


class PluginDatasetCreateDialog(QDialog, FORM_CLASS):
    """
    This class is a simple Dialog to give the details for a (NDFF) Dataset.

    It's called from the 'Dataset (chooser) dialog' which holds all logic for the creation of the actual Dataset,
    and retrieves the details from this PluginDatasetCreateDialog instance.
    """
    def __init__(self, parent=None):
        """
        Constructor (setting up the UI/dialog based on the .ui file)
        """
        super(PluginDatasetCreateDialog, self).__init__(parent)
        self.setupUi(self)
        self.cb_dataset_layer.setFilters(QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.LineLayer | QgsMapLayerProxyModel.PolygonLayer)
        self.cb_dataset_layer.setAllowEmptyLayer(True, text='Kies een QGIS data/kaartlaag met 1(!) (geselecteerde) geometrie')
        self.cb_dataset_layer.setCurrentIndex(0)
        self.cb_dataset_layer.layerChanged.connect(self.dataset_layer_changed)
        self.location = None

    def dataset_layer_changed(self, layer: QgsMapLayerProxyModel) -> None:
        """
        This method is called when the dataset layer changes in the dataset create dialog.

        It checks IF the layer that is selected, either
        - has just one Feature
        or
        - has just one Feature SELECTED

        """
        layer = self.cb_dataset_layer.currentLayer()
        feature = QgsFeature()
        if layer is None:
            # OK
            self.cb_dataset_layer.setCurrentIndex(0)
            return

        # the cb_dataset_layer has a filter for ONLY (vector) Line- or Polgyon-layers, so just check for features
        if layer.featureCount() == 1:
            layer.getFeatures().nextFeature(feature)
        elif layer.selectedFeatureCount() == 1:
            feature = layer.selectedFeatures()[0]
        else:
            QMessageBox.warning(self, PLUGIN_DIALOGS_TITLE,
                                "De laag voor de Dataset/Map mag maar 1 Feature/Geometrie bevatten, \n"
                                "OF\ner mag maar 1 Feature/Geometrie in de laag zijn geselecteerd!")
            self.cb_dataset_layer.setCurrentIndex(0)
            return

        o = NdffObservation()  # silly placeholder to be able to use parse_wkt_wkb
        NdffConnector.parse_wkt_wkb(o, feature.geometry().asWkt())
        precision = 5
        if NdffConnector.get_crs(o) == NdffConnector.EPSG_28992:
            precision = 1
        NdffConnector.parse_wkt_wkb(o, feature.geometry().asWkt(precision=precision))  # second round, to get the precision right...
        self.location = o.location
        if 'olygon' in feature.geometry().asWkt():
            # (Multi)Polygons should have a buffer of 0, all others we set to 10
            self.location["buffer"] = 0
            # also check max area
            msg = ("De NDFF verwacht geen onderzoekslocaties groter dan 1.700 km².\n"
                   "De QGIS-connector is niet bedoeld voor het verwerken van zulke grote datasets.\n\n"
                   "Neem contact op met de NDFF om de mogelijkheden te bespreken.")
            if NdffConnector.get_crs(o) == NdffConnector.EPSG_28992 and feature.geometry().area() > 1700000000:
                QMessageBox.warning(self, PLUGIN_DIALOGS_TITLE, msg)
            elif NdffConnector.get_crs(o) == NdffConnector.EPSG_4326 and feature.geometry().area() > 0.25:
                QMessageBox.warning(self, PLUGIN_DIALOGS_TITLE, msg)
        else:
            # lines and points have buffer of 10
            self.location["buffer"] = 10

        tmp_dataset = NdffDataset()  # creating a dataset here, pure for proper visualisation
        tmp_dataset.set("location", self.location)
        self.lbl_current_location.setText(f"Locatie  -->  {tmp_dataset.get('location')}")

        log.debug(f"Created dataset location: {self.location}")

    def accept(self) -> None:
        """
        Qt api call: called when the user clicks OK or other ways accepts the dialog
        """
        log.debug('OK clicked; DatasetCreate dialog')
        self.done(QDialog.Accepted)
