# -*- 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 copy
import json
import threading

from qgis.core import QgsMessageLog, QgsProject, QgsVectorLayer, QgsJsonUtils, QgsField, QgsFields, QgsVectorFileWriter, QgsCoordinateTransformContext
from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtCore import QCoreApplication, QSettings, QTranslator
from qgis.PyQt.QtWidgets import QDialog, QTableWidgetItem, QLabel

from PyQt5.uic import loadUi
from PyQt5 import QtCore, QtGui, QtWidgets

from jsonschema import Draft7Validator

from ...form.textfield import TextField
from ..dropdown import DropDown
from ..array_field import ArrayField
from ..boolean import Boolean

import math


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


class ObjectView(QtWidgets.QWidget, UI_CLASS):
    inputChanged = QtCore.pyqtSignal(object, str)

    def __init__(self, interface, json, schema, key, inheritedErrors = []):
        """Constructor."""

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

        self.setupUi(self)

        self.json = json
        self.key = key
        self.schema = schema
        self.inheritedErrors = inheritedErrors

        self.validationTimer = None


        if self.key not in self.json:
            self.json[self.key] = {}

        self.fieldArray = []


        self.lfbObjectGroup.setTitle(self.schema['title'])
        if self.findChild(QtWidgets.QWidget, 'lfbObjectGroup'):
            if 'title' in schema:
                self.lfbObjectGroup.setTitle(schema['title'])
            else:
                self.lfbObjectGroup.setTitle('')
        
        items = schema['properties'].items()

        row = 0
        column = 0
        columnSpan = 1

        for attr, value in items:

            if attr not in self.json[self.key]:
                self.json[self.key][attr] = None

            valueType = value['type']

            if 'enum' in value:
                field = DropDown(interface, self.json, value, attr)
            elif valueType == 'boolean':
                field = Boolean(interface, self.json[self.key], value, attr)
                #field.lfbInfoBox.connect(self.infoBoxClicked)
            else:
                field = TextField(interface, self.json[self.key], value, attr)

            if '$FIMColumn' in value:
                column = value['$FIMColumn']
                if column == 0:
                    row += 1
                columnSpan = 1
            else:
                row += 1
                column = 0
                columnSpan = -1

            
            self.lfbFormObject.addWidget(field, row, column, 1, columnSpan) #row, column
            field.inputChanged.connect(self.onInputChanged)
            
            self.fieldArray.append(field)


        self.show()

    def setSchemaErrors(self, schemaErrors):
        self.schemaErrors = schemaErrors

    def emitInputChanged(self):
        #self.inputChanged.emit(self.json[self.key], self.key)
        pass

    def onInputChanged(self, newJson, key=None):
        """Child input changed."""
        #self.inputChanged.emit(self.json[self.key], self.key)
        pass

        self.json[self.key][key] = newJson

        self.validate()
        pass
    
    def setJson(self, newJson, setFields = True):



        self.json = newJson

        if self.key not in self.json:
            self.json[self.key] = {}

        for field in self.fieldArray :
            
            field.setJson(self.json[self.key], setFields)

        
        #self.validate()
    
    def validate(self):

        self.lfbObjectGroup.setStyleSheet('QGroupBox#lfbObjectGroup{ padding: 10px; background: rgba(0,0,0,0.1);border-radius: 10px; border: 2px solid green;}')

        errors = []
        self.inheritedErrors.clear()
        
        v = Draft7Validator(self.schema)
        errors = sorted(v.iter_errors(self.json[self.key]), key=lambda e: e.path)

        if len(errors) == 0 and (self.key == 'kraut' or self.key == 'grass' or self.key == 'farne' or self.key == 'doldengewaechse' or self.key == 'beerenstraucher' or self.key == 'grosstraucher'):
            self.check100(self.key)

        
            
        self.updateErrors()
    
    def check100(self, key):
        
        currentValue = 0

        for item in self.json[key].items():
            currentValue += item[1]
    
        if currentValue > 100:
            self.lfbObjectGroup.setStyleSheet('QGroupBox#lfbObjectGroup{ padding: 10px; background: rgba(0,0,0,0.1);border-radius: 10px; border: 2px solid red;}')
            self.inheritedErrors.append({
                'message': 'Die Summe der Prozentangaben darf nicht größer als 100 sein.',
            })

        

    def updateErrors(self):
        for i in reversed(range(self.lfbErrorWidget.count())): 
            self.lfbErrorWidget.itemAt(i).widget().setParent(None)

        for error in self.inheritedErrors:
            label = QLabel(error['message'])
            label.setStyleSheet('QLabel { font-size: 15px; color: red; padding: 5px; margin: 10px; background-color: rgba(0,0,0,0.3); border-radius: 5px;}')
            self.lfbErrorWidget.addWidget(label)