# -*- coding: utf-8 -*-

__author__ = '(C) 2023 by Gerald Kogler'
__date__ = '1/10/2023'
__copyright__ = 'Copyright 2023, 300.000 Km/s'
__license__ = 'GPLv3 license'

import os

from qgis.PyQt import uic
from qgis.PyQt import QtWidgets
from qgis.PyQt.QtWidgets import QLineEdit, QPlainTextEdit, QComboBox, QCheckBox, QSpinBox, QPushButton, QDialogButtonBox
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsProject, Qgis
from .utils import Utils

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'qwv_dialog11_layers.ui'))

class QWVDialog11(QtWidgets.QDialog, FORM_CLASS):

    def __init__(self, iface, parent=None):
        """Constructor."""
        super(QWVDialog11, self).__init__(parent)
        # Set up the user interface from Designer through FORM_CLASS.
        # After self.setupUi() you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect

        self.iface = iface
        self.parent = parent
        self.first_start = True
        self.setupUi(self)

        # add buttons
        self.closeBtn = QPushButton(Utils.getIcon("window-close"), Utils.tr("Cancel"))
        self.button_box.addButton(self.closeBtn, QDialogButtonBox.ActionRole)

        self.saveBtn = QPushButton(Utils.getIcon("dialog-apply"), Utils.tr("Ok"))
        self.button_box.addButton(self.saveBtn, QDialogButtonBox.ActionRole)


    def addRowLayer(self, viewId, viewLayer):
        """Add row to layer table."""

        index = self.dialog11_layers.rowCount()
        self.dialog11_layers.insertRow(index)

        # id
        dialog11_layers_layer = QLineEdit()
        dialog11_layers_layer.setText(viewLayer["name"])
        dialog11_layers_layer.setToolTip(viewLayer["id"])
        dialog11_layers_layer.setReadOnly(True)
        self.dialog11_layers.setCellWidget(index, 0, dialog11_layers_layer)

        # name
        dialog11_layers_name = QLineEdit()
        dialog11_layers_name.setText(viewLayer["name"])
        self.dialog11_layers.setCellWidget(index, 1, dialog11_layers_name)

        # description
        dialog11_layers_description = QPlainTextEdit()
        dialog11_layers_description.appendPlainText(viewLayer["description"])
        self.dialog11_layers.setCellWidget(index, 2, dialog11_layers_description)

        # legend
        dialog11_layers_legend = QCheckBox()
        dialog11_layers_legend.setChecked(viewLayer["legend"])
        self.dialog11_layers.setCellWidget(index, 3, dialog11_layers_legend)

        #self.dialog1_layers_legend_cell = QTableWidgetItem()
        #self.dialog1_layers_legend_cell.setTextAlignment(QgsLayoutAligner.AlignHCenter)
        #self.dialog1_views.setItem(index, 3, self.dialog1_layers_legend_cell)


    def getSelectedViewRow(self):
        """Get index of selected row from layer table."""

        return self.dialog11_layers.selectionModel().selectedRows()[0].row()


    def loadData(self, viewListIndex, viewId, viewName):
        """Fill UI with layer data."""

        #print("loadData for row: ", viewListIndex, viewId, viewName)

        self.layersBox.setTitle("Configure layers for view '" + viewName + "'")

        # remove rows from table
        self.dialog11_layers.setRowCount(0)

        # load all layers for this view
        for layer in QgsProject.instance().mapThemeCollection().mapThemeVisibleLayers(viewName):

            # only add vector layers in order to ignore raster layers
            if str(layer.type()) == 'LayerType.Vector':

                viewLayer = {
                    "id": layer.id(),   # use internal layer id
                    "name": self.getSavedViewLayer(viewListIndex, layer, "name"),
                    "description": self.getSavedViewLayer(viewListIndex, layer, "description"),
                    "legend": self.getSavedViewLayer(viewListIndex, layer, "legend")
                }

                #print("addRowView", viewLayer)
                self.addRowLayer(viewId, viewLayer)


    def getSavedViewLayer(self, index, layer, param):
        """Return saved parameters of views layers."""

        viewLayers = self.parent.dialog1_views.layers[index]
        default = {
            "name": layer.name(),
            "description": "",
            "legend": False
        }

        # not yet saved -> return default
        if viewLayers == None:
            return default[param]

        # already saved, get parameter
        for viewLayer in viewLayers:
            if viewLayer["id"] == layer.id():
                return viewLayer[param]

        # default
        return default[param]


    def saveData(self, viewIndex):
        """Save views layers."""

        if self.uniqueLayerNames():

            #print("saveData for row:", viewIndex, self.dialog11_layers.rowCount())

            self.parent.dialog1_views.layers[viewIndex] = []
            for i in range(self.dialog11_layers.rowCount()):
                layerId = self.dialog11_layers.cellWidget(i, 0).toolTip()
                layerName = self.dialog11_layers.cellWidget(i, 1).text()
                layerDescription = self.dialog11_layers.cellWidget(i, 2).toPlainText()
                layerLegend = self.dialog11_layers.cellWidget(i, 3).isChecked()

                #print("saveData", layerId, layerName, layerDescription, layerLegend)

                self.parent.dialog1_views.layers[viewIndex].append({
                    "id": layerId, 
                    "name": layerName, 
                    "description": layerDescription, 
                    "legend": layerLegend
                })

            self.hide()

        else:
            self.messageBar.pushMessage(Utils.tr("Warning"), Utils.tr("Layer names must be unique."), level=Qgis.Warning, duration=3)


    def uniqueLayerNames(self):
        """Compare all layer names to assure that they are unique."""

        layerNames = []
        for i in range(self.dialog11_layers.rowCount()):
            layerNames.append(self.dialog11_layers.cellWidget(i, 1).text())

        # print(len(layerNames), len(set(layerNames)))

        return not len(layerNames) > len(set(layerNames))