# -*- 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
from PyQt5 import QtCore

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 = 0

        self.currentFeature = None

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

        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 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 = len(errors)


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

        return len(errors) == 0
