# -*- coding: utf-8 -*-
"""
/***************************************************************************
 LfbRegenerationWildlifeImpactDialog
                                 A QGIS plugin
 Lfb Regeneration and Wildlife Impact Monitoring
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2023-05-08
        git sha              : $Format:%H$
        copyright            : (C) 2023 by Grünecho
        email                : support@grunecho.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 os
import json

from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtWidgets import QDialog, QScrollArea, QWidget, QFormLayout, QGridLayout, QVBoxLayout, QGroupBox, QLabel, QSizePolicy

from PyQt5 import QtCore
from qgis.core import QgsMessageLog

from ...utils.helper import Utils


UI_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'saveBar.ui'))


class SaveBar(QtWidgets.QWidget, UI_CLASS):
    """Implementation of the SaveBar widget."""

    saveFeature = QtCore.pyqtSignal(object, bool)
    toHome = QtCore.pyqtSignal(bool)
    devButton = QtCore.pyqtSignal(bool)

    def __init__(self, interface, json):
        """Constructor."""

        QDialog.__init__(self, interface.mainWindow())

        self.setupUi(self)

        self.interface = interface
        self.json = json

        self.isValidating = True
        self.isValid = False

        self.maxErrors = 0
        self.currentErrors = []

        self.currentFeature = None

        self.lfbSaveBtn.setDisabled(True)
        self.lfbSaveBtn.clicked.connect(self.saveBtnClicked)

        self.lfb_error_btn.hide()
        self.lfb_error_btn.clicked.connect(self.openErrorDialog)

        self.lfbDevBtn.hide()
        
        self.lfbHomeBtn.clicked.connect(self.openHome)

        self.lfbSchemaBtn.hide()
        self.lfbErrorDialogBtn.hide()
        
        self.lfbProgressBar.hide()
        self.lfbProgressBar.setValue(100)

        self.lfbActionRow.setContentsMargins(0,0,0,0)
        self.lfbProgressBar.setContentsMargins(0,0,0,0)

        self.lfbFokusFeature.hide()
        self.lfbFokusFeature.clicked.connect(self.focusFeature)

        self.showMetaData()

        self.show()

    def showMetaData(self):
        """Show/set the plugin version."""
        metaData = Utils.getMetaData()
        self.lfbPluginVersion.setText('Version: ' + str(metaData['version']))

    def focusFeature(self):
        """Focus the current feature."""
        Utils.focusFeature(self.interface, self.currentFeature, True, 1000)

        
    def openHome(self):
        """Open the home widget."""

        self.saveFeature.emit(self.json, False)

    def saveBtnClicked(self):
        """Save the feature."""

        self.saveFeature.emit(self.json, True)
        self.lfbFokusFeature.show()

    def openErrorDialog(self):
        """Open the error dialog."""

        QgsMessageLog.logMessage('Open Error Dialog', 'FIM')
        #https://www.pythonguis.com/tutorials/pyqt-dialogs/

        dlg = QDialog(self)
        dlg.setWindowTitle("Fehler")
        main_layout = QVBoxLayout()

        dlg.setLayout(main_layout)

        ## Add scroll area
        scrollArea = QScrollArea()
        scrollArea.setMinimumSize(400, 400)
        #scroll.grabGesture(dlg)
        main_layout.addWidget(scrollArea)


        layout = QVBoxLayout()
        scrollArea.setLayout(layout)

        ## List currentErrors
        for error in self.currentErrors:

            ## Add error validator_value
            #QgsMessageLog.logMessage(str(error.relative_schema_path), 'FIM')
            #validator_value = QLabel(' '.join(error.relative_schema_path))
            #layout.addWidget(validator_value)

            ## Add error message
            message = QLabel(error.message)
            message.sizePolicy().setVerticalPolicy(QSizePolicy.Fixed)
            layout.addWidget(message)

            ## Add horizontal line
            line = QtWidgets.QFrame()
            line.setFrameShape(QtWidgets.QFrame.HLine)
            line.setFrameShadow(QtWidgets.QFrame.Sunken)
            layout.addWidget(line)


        

        dlg.exec()

        #self.interface.openErrorDialog()

    def setAttributes(self,feature, key):
        """Set feature ID."""

        self.currentFeature = feature

        layer = Utils.getLayerById()
        fields = layer.fields()
        idx = fields.indexFromName(key)
        self.lfbId.setText(str(feature.attributes()[idx]))

        self.lfbFokusFeature.show()


    def validate(self, errors = []):
        """En- or disable the save button."""

        self.maxErrors = max(self.maxErrors, len(errors))
        self.currentErrors = errors
        
        
        for error in errors:
            QgsMessageLog.logMessage(str(error), 'FIM - validation')

        if len(errors) == 0:
            self.lfbErrorDialogBtn.setText('')
            self.lfbSaveBtn.setDisabled(False)
            self.lfb_error_btn.hide()
        else:
            self.lfbSaveBtn.setDisabled(True)
            self.lfb_error_btn.hide() # CHANGE
            self.lfbErrorDialogBtn.setText(str(len(errors)) + ' verbleibende Fehler.')
       

        return len(errors) == 0
