"""
/***************************************************************************
 DICTDialogConfig
                                 A QGIS plugin
 DICT
                             -------------------
        begin                : 2015-08-19
        git sha              : $Format:%H$
        copyright            : (C) 2015 by Loïc BARTOLETTI
    + some random trainee in 2019 who adapted the whole code in Py3 for free
        email                : lbartoletti@tuxfamily.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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

from PyQt5 import uic
from PyQt5.QtCore import QDir, QFileInfo, QSettings
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QFileDialog, QMessageBox
from qgis.core import QgsApplication, QgsProject

from .dict_email import DictEmail
from .utils import Utils

FORM_CLASS, _ = uic.loadUiType(
    os.path.join(os.path.dirname(__file__), "DICT_dialog_config.ui")
)


class DICTDialogConfig(QDialog, FORM_CLASS):
    def __init__(self, iface, dico_crs, parent=None):
        """Constructor."""
        super(DICTDialogConfig, self).__init__(parent)
        # Set up the user interface from Designer.
        # After 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.setupUi(self)

        self.iface = iface
        if QgsProject.instance().crs().authid() in dico_crs:
            self.comboBoxDbCoordinatesReferenceSystem.setCurrentText(
                dico_crs[QgsProject.instance().crs().authid()]
            )
        else:
            self.comboBoxDbCoordinatesReferenceSystem.setCurrentIndex(0)

        self.configRep.setText(QSettings().value("/DICT/configRep", QDir.homePath()))
        self.configXML.setText(QSettings().value("/DICT/configXML", QDir.homePath()))
        self.configQPT.setText(
            QSettings().value(
                "/DICT/configQPT",
                os.path.join(
                    QgsApplication.qgisSettingsDirPath(), "composer_templates"
                ),
            )
        )
        self.configAnnexes.setText(
            QSettings().value(
                "/DICT/configAnnexes",
                os.path.join(
                    QgsApplication.qgisSettingsDirPath(), "python/plugins/DICT/annexes"
                ),
            )
        )

        self.signSignature.setText(QSettings().value("/DICT/signSignature"))
        self.signNom.setText(QSettings().value("/DICT/signNom"))
        self.respTel.setText(QSettings().value("/DICT/respTel"))
        self.respService.setText(QSettings().value("/DICT/respService"))
        self.respNom.setText(QSettings().value("/DICT/respNom"))
        self.coordFax.setText(QSettings().value("/DICT/coordFax"))
        self.coordTel.setText(QSettings().value("/DICT/coordTel"))
        self.coordCommune.setText(QSettings().value("/DICT/coordCommune"))
        self.coordCP.setText(QSettings().value("/DICT/coordCP"))
        self.coordBP.setText(QSettings().value("/DICT/coordBP"))
        self.coordNumVoie.setText(QSettings().value("/DICT/coordNumVoie"))
        self.coordPersonne.setText(QSettings().value("/DICT/coordPersonne"))
        self.coordDenom.setText(QSettings().value("/DICT/coordDenom"))
        self.TelEndommagement.setText(QSettings().value("/DICT/TelEndommagement"))

        self.prefRecep.setText(QSettings().value("/DICT/prefRecep"))
        self.sufRecep.setText(QSettings().value("/DICT/sufRecep"))
        self.prefPlan.setText(QSettings().value("/DICT/prefPlan"))
        self.sufPlan.setText(QSettings().value("/DICT/sufPlan"))

        self.lineEditEchellesPlans.setText(QSettings().value("/DICT/echellesPlans"))

        # database storage
        self.groupBoxDbStorage.setEnabled(False)
        self.checkBoxDbStorage.setChecked(
            QSettings().value("/DICT/dbStorage", False, type=bool)
        )
        self.groupBoxDbStorage.setEnabled(
            QSettings().value("/DICT/dbStorage", False, type=bool)
        )

        self.comboBoxDbType.setCurrentText(QSettings().value("/DICT/dbType"))
        self.comboBoxDbConnection.setCurrentText(
            QSettings().value("/DICT/dbConnection")
        )
        self.comboBoxDbSchema.setCurrentText(QSettings().value("/DICT/dbSchema"))
        self.comboBoxDbCoordinatesReferenceSystem.setCurrentText(
            QSettings().value("/DICT/dbCoordinatesReferenceSystem")
        )
        self.lineEditDbNomCoucheDeclarations.setText(
            QSettings().value("/DICT/dbNomCoucheDeclarations")
        )
        self.lineEditDbNomCoucheReponses.setText(
            QSettings().value("/DICT/dbNomCoucheReponses")
        )

        self.Endommagement.setText(QSettings().value("/DICT/Endommagement"))

        # envoi courriel
        self.groupBoxSmtp.setEnabled(False)
        self.checkBoxSendEmail.setChecked(
            QSettings().value("/DICT/envoyerCourriel", False, type=bool)
        )
        self.groupBoxSmtp.setEnabled(
            QSettings().value("/DICT/envoyerCourriel", False, type=bool)
        )

        self.lineEditSmtpDescription.setText(QSettings().value("/DICT/smtpDescription"))
        self.lineEditSmtpNom_complet.setText(QSettings().value("/DICT/smtpNomComplet"))
        self.lineEditSmtpNom_du_serveur.setText(
            QSettings().value("/DICT/smtpNomDuServeur")
        )
        self.lineEditSmtpPort.setText(QSettings().value("/DICT/smtpPort"))
        self.lineEditSmtpUtilisateur.setText(QSettings().value("/DICT/smtpUtilisateur"))
        self.lineEditSmtpMot_de_passe.setText(QSettings().value("/DICT/smtpMotDePasse"))
        self.comboBoxSmtpSecurite.setCurrentText(
            QSettings().value("/DICT/smtpSecurite")
        )
        self.plainTextEditSmtpTextBody.setPlainText(
            QSettings().value("/DICT/smtpCorpsTexte", DictEmail.defaultTextBody())
        )
        if self.plainTextEditSmtpTextBody.toPlainText() == "":
            self.plainTextEditSmtpTextBody.setPlainText(DictEmail.defaultTextBody())
        self.plainTextEditSmtpHtmlBody.setPlainText(
            QSettings().value("/DICT/smtpCorpsHtml", DictEmail.defaultHtmlBody())
        )
        if self.plainTextEditSmtpHtmlBody.toPlainText() == "":
            self.plainTextEditSmtpHtmlBody.setPlainText(DictEmail.defaultHtmlBody())
        self.lineEditSmtpUrlReponse.setText(QSettings().value("/DICT/smtpUrlReponse"))

        self.creationPDF_toujours.setChecked(
            QSettings().value("/DICT/creationPDF_toujours", False, type=bool)
        )

        self.fusionPDF.setChecked(
            QSettings().value("/DICT/fusionPDF", False, type=bool)
        )

        self.pdftk.setFilePath(QSettings().value("/DICT/configPDFTK"))
        self.usePdftk.setChecked(QSettings().value("/DICT/usePDFTK", False, type=bool))
        self.checkBoxSendEmail.stateChanged.connect(self.setEmailSending)
        self.toolButton.pressed.connect(lambda: self.showDialogConfig(self.configRep))
        self.toolButtonXML.pressed.connect(
            lambda: self.showDialogConfig(self.configXML)
        )
        self.toolButtonQPT.pressed.connect(
            lambda: self.showDialogConfig(self.configQPT)
        )
        self.toolButtonAnnexes.pressed.connect(
            lambda: self.showDialogConfig(self.configAnnexes)
        )

        self.okButton = self.button_box.button(QDialogButtonBox.Ok)
        self.okButton.clicked.connect(self.accept)

        self.cancelButton = self.button_box.button(QDialogButtonBox.Cancel)
        self.cancelButton.clicked.connect(self.close)

        self.pushButtonTesterConnexionSmtp.clicked.connect(self.testSmtpConnection)

    def showDialogConfig(self, obj, flags="Directory"):
        if flags == "Directory":
            fname = QFileDialog.getExistingDirectory(self, "Choisissez un répertoire :")
        elif flags == "Executable":
            fname, _ = QFileDialog.getOpenFileName(self, "Choisissez l'exécutable :")
        else:
            return

        if fname:
            obj.setText(fname)

    def rep(self, repertoire, nom):
        rep = repertoire.text()
        if rep:
            if QFileInfo(rep).exists():
                QSettings().setValue("/DICT/" + nom, rep)
            elif Utils.stringContainsVariable(rep):
                QSettings().setValue("/DICT/" + nom, rep)
            else:
                if str(QFileInfo(rep).path()) != ".":
                    QSettings().setValue("/DICT/" + nom, QFileInfo(rep).path())
                else:
                    QSettings().setValue("/DICT/" + nom, QDir.homePath())
        else:
            QSettings().setValue("/DICT/" + nom, QDir.homePath())
        repertoire.setText(QSettings().value("/DICT/" + nom))

    def fullpath(self, full_path, name):
        fullpath = full_path.text()
        if fullpath:
            print("name: ", name, "fullpath: ", fullpath)
            if QFileInfo(fullpath).exists():
                print("setValue: ", "/DICT/" + name, ", ", fullpath)
                QSettings().setValue("/DICT/" + name, fullpath)

    def accept(self):
        if not self.lineEditDbNomCoucheDeclarations.text():
            self.lineEditDbNomCoucheDeclarations.setText("Déclarations")

        if not self.lineEditDbNomCoucheReponses.text():
            self.lineEditDbNomCoucheReponses.setText("Réponses")

        self.rep(self.configRep, "configRep")
        self.rep(self.configXML, "configXML")
        self.rep(self.configQPT, "configQPT")
        self.rep(self.configAnnexes, "configAnnexes")

        QSettings().setValue("/DICT/signSignature", self.signSignature.text())
        QSettings().setValue("/DICT/signNom", self.signNom.text())
        QSettings().setValue("/DICT/respTel", self.respTel.text())
        QSettings().setValue("/DICT/respService", self.respService.text())
        QSettings().setValue("/DICT/respNom", self.respNom.text())
        QSettings().setValue("/DICT/coordFax", self.coordFax.text())
        QSettings().setValue("/DICT/coordTel", self.coordTel.text())
        QSettings().setValue("/DICT/coordCommune", self.coordCommune.text())
        QSettings().setValue("/DICT/coordCP", self.coordCP.text())
        QSettings().setValue("/DICT/coordBP", self.coordBP.text())
        QSettings().setValue("/DICT/coordNumVoie", self.coordNumVoie.text())
        QSettings().setValue("/DICT/coordPersonne", self.coordPersonne.text())
        QSettings().setValue("/DICT/coordDenom", self.coordDenom.text())
        QSettings().setValue("/DICT/TelEndommagement", self.TelEndommagement.text())
        QSettings().setValue("/DICT/Endommagement", self.Endommagement.text())
        QSettings().setValue("/DICT/prefRecep", self.prefRecep.text())
        QSettings().setValue("/DICT/sufRecep", self.sufRecep.text())
        QSettings().setValue("/DICT/prefPlan", self.prefPlan.text())
        QSettings().setValue("/DICT/sufPlan", self.sufPlan.text())

        QSettings().setValue("/DICT/echellesPlans", self.lineEditEchellesPlans.text())

        # database storage
        QSettings().setValue("/DICT/dbStorage", self.checkBoxDbStorage.isChecked())

        QSettings().setValue("/DICT/dbType", self.comboBoxDbType.currentText())
        QSettings().setValue(
            "/DICT/dbConnection", self.comboBoxDbConnection.currentText()
        )
        QSettings().setValue("/DICT/dbSchema", self.comboBoxDbSchema.currentText())
        QSettings().setValue(
            "/DICT/dbCoordinatesReferenceSystem",
            self.comboBoxDbCoordinatesReferenceSystem.currentText(),
        )
        QSettings().setValue(
            "/DICT/dbNomCoucheDeclarations", self.lineEditDbNomCoucheDeclarations.text()
        )
        QSettings().setValue(
            "/DICT/dbNomCoucheReponses", self.lineEditDbNomCoucheReponses.text()
        )

        # send email
        if self.checkBoxSendEmail.isChecked():
            is_checked = DictEmail.checkSmtpAccount(
                self.iface,
                self.lineEditSmtpNom_du_serveur.text(),
                self.lineEditSmtpPort.text(),
                self.lineEditSmtpUtilisateur.text(),
                self.lineEditSmtpMot_de_passe.text(),
                self.comboBoxSmtpSecurite.currentText(),
                False,
            )
            QSettings().setValue("/DICT/envoyerCourriel", is_checked)
            if is_checked != self.checkBoxSendEmail.isChecked():
                self.checkBoxSendEmail.setChecked(is_checked)
        QSettings().setValue(
            "/DICT/smtpDescription", self.lineEditSmtpDescription.text()
        )
        QSettings().setValue(
            "/DICT/smtpNomComplet", self.lineEditSmtpNom_complet.text()
        )
        QSettings().setValue(
            "/DICT/smtpNomDuServeur", self.lineEditSmtpNom_du_serveur.text()
        )
        QSettings().setValue("/DICT/smtpPort", self.lineEditSmtpPort.text())
        QSettings().setValue(
            "/DICT/smtpUtilisateur", self.lineEditSmtpUtilisateur.text()
        )
        QSettings().setValue(
            "/DICT/smtpMotDePasse", self.lineEditSmtpMot_de_passe.text()
        )
        QSettings().setValue(
            "/DICT/smtpSecurite", self.comboBoxSmtpSecurite.currentText()
        )
        QSettings().setValue(
            "/DICT/smtpCorpsTexte", self.plainTextEditSmtpTextBody.toPlainText()
        )
        if QSettings().value("/DICT/smtpCorpsTexte") == "":
            QSettings().setValue("/DICT/smtpCorpsText", DictEmail.defaultTextBody())
        QSettings().setValue(
            "/DICT/smtpCorpsHtml", self.plainTextEditSmtpHtmlBody.toPlainText()
        )
        if QSettings().value("/DICT/smtpCorpsHtml") == "":
            QSettings().setValue("/DICT/smtpCorpsHtml", DictEmail.defaultHtmlBody())
        QSettings().setValue("/DICT/smtpUrlReponse", self.lineEditSmtpUrlReponse.text())

        QSettings().setValue("/DICT/creationPDF_toujours", self.creationPDF_toujours.isChecked())
        QSettings().setValue("/DICT/fusionPDF", self.fusionPDF.isChecked())

        QSettings().setValue("/DICT/configPDFTK", self.pdftk.filePath())
        QSettings().setValue("/DICT/usePDFTK", self.usePdftk.isChecked())
        self.close()

        return QDialog.Accepted

    def setEmailSending(self):
        if self.checkBoxSendEmail.isChecked():
            self.groupBoxSmtp.setEnabled(True)
        else:
            self.groupBoxSmtp.setEnabled(False)

    def testSmtpConnection(self):
        server = self.lineEditSmtpNom_du_serveur.text()
        user = self.lineEditSmtpUtilisateur.text()
        if not server:
            server = "?"
        if not user:
            user = "?"
        if DictEmail.checkSmtpAccount(
            self.iface,
            server,
            self.lineEditSmtpPort.text(),
            user,
            self.lineEditSmtpMot_de_passe.text(),
            self.comboBoxSmtpSecurite.currentText(),
        ):
            msg = "Connexion de {} sur {} réussie".format(user, server)
        else:
            msg = "Échec de la connexion de {} sur {}".format(user, server)

        msgBox = QMessageBox()
        msgBox.setWindowTitle("Test connexion SMTP")
        msgBox.setText(msg)
        msgBox.exec_()
