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

from qgis.core import QgsMessageLog, QgsProject, QgsWkbTypes, QgsVectorFileWriter, QgsFeature, QgsGeometry, QgsPointXY
from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtWidgets import QDialog
from qgis.PyQt.QtCore import QDateTime, QJsonDocument
from PyQt5.QtNetwork import  QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PyQt5.QtCore import QCoreApplication, QUrl


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

from ..utils.helper import Utils


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

CHANGE_UNTERLOSNR = "https://db01.simplex4data.de/projekte/lfb/postgrest/rpc/update_unterlosnummern"

class UnterlosnrDialog(QDialog, UI_CLASS):

    token_changed = QtCore.pyqtSignal(str)
    set_unterlosnummer = QtCore.pyqtSignal(str)

    def __init__(self, parent=None, features=None, token=None):
        """Constructor."""

        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.token = token
        self.features = features
        self.unterlosnr_new = ''

        #unterlos_nr = str(feature['unterlosnr']) 
        unterlos_nr = '' # if unterlos_nr == 'NULL' else unterlos_nr
        # Set unterlos_nr if feature is a QgsFeature and contains 'unterlosnr'
        #if feature and isinstance(feature, QgsFeature) and 'unterlosnr' in feature.fields().names():
        #    unterlos_nr = feature['unterlosnr']


        self.change_btn_send.clicked.connect(lambda: self._save_unterlosnr(features))

        los_ids = self._array_from_features(features)

        self.losnummer_old.setText(str(los_ids))
        self.losnummer_new.setText(unterlos_nr)

        self.unterlosnr_error_label.setStyleSheet("color: red")
        #if feature['los_id'] == 'NULL':
        #    self.unterlosnr_error_label.setText("Keine Unterlosnummer vorhanden")
        #    self.change_btn_send.setEnabled(False)
        if self.token is None:
            self.unterlosnr_error_label.setText(f'Login first')
            self.change_btn_send.setEnabled(False)
        else:
            self.unterlosnr_error_label.setText(f'')
            self.change_btn_send.setEnabled(True)

    def _array_from_features(self, features):
        los_ids = []
        for feature in features:
            # appen feature['los_id'] as integer
            los_ids.append(int(feature['los_id']))
        return los_ids
    
    def _save_unterlosnr(self, features=None):
        """
        Save the unterlosnr
        """

        unterlosnr_old = self.losnummer_old.text()
        self.unterlosnr_new = self.losnummer_new.text()

        if unterlosnr_old == self.unterlosnr_new:
            self.unterlosnr_error_label.setText("Unterlosnummern sind gleich")
            return
        
        try:

            # create array of all 'los_ids' of features
            los_ids = self._array_from_features(features)


            json = {
                #"p_id_g_los": feature['los_id'],
                "p_id_g_los": los_ids,
                "p_unterlosnr": self.unterlosnr_new
            }
            document = QJsonDocument(json)

            request = QNetworkRequest(QUrl(CHANGE_UNTERLOSNR))
            request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
            request.setRawHeader(b"Authorization", f"Bearer {self.token}".encode())

            self.nam = QNetworkAccessManager()
            #self.nam.finished.disconnect()
            self.nam.finished.connect(self.handleResponse)
            self.nam.post(request, document.toJson())

        except Exception as e:
            QgsMessageLog.logMessage(e)


    ## OLD
    def set_token(self, token=None):
        self.token = token
        self.token_changed.emit(self.token)

    def enable_send_btn(self, reset=False):
        self.change_btn_send.setEnabled(True)
        self.change_btn_send.setText("Senden")
        self.change_btn_send.repaint()
        
    def handleResponse(self, reply):
        """
        Handle the response from the server.
        """
        
        if reply.error():
            self.unterlosnr_error_label.setText(f'Failed: {reply.errorString}')
            self.enable_send_btn(True)
            return
        
        response = json.loads(reply.readAll().data().decode())

        if response != None:
            self.unterlosnr_error_label.setText('')
            self.enable_send_btn(True)
            Utils.update_unterlosnummern(self.features, self.unterlosnr_new)
            self.set_unterlosnummer.emit(self.unterlosnr_new)
            self.close()
            return
        else:
            self.unterlosnr_error_label.setText("Umbenennung fehlgeschlagen")
            self.enable_send_btn(True)