from PyQt6 import QtCore, QtGui, QtWidgets
from src import Icon, settings, logger
from .dialog_sources.Ui_settings import Ui_Dialog as _settings
from src.ui.widgets.iconLine import IconWidget

base = """'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">

    <html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style
    type="text/css">

    p, li { white-space: pre-wrap; }

    hr { height: 1px; border-width: 0; }

    li.unchecked::marker { content: "\2610"; }

    li.checked::marker { content: "\2612"; }

    </style></head><body style=" font-family:''Segoe UI''; font-size:9pt; font-weight:400;
    font-style:normal;">

    <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px;
    margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html>'"""


class Settings(QtWidgets.QDialog, _settings):
    def __init__(self, user=None):
        super().__init__()
        self.setupUi(self)
        self.password.setEchoMode(QtWidgets.QLineEdit.EchoMode.Normal)
        self.zotero_api_key.setEchoMode(QtWidgets.QLineEdit.EchoMode.Normal)
        self.editSignature.setAcceptRichText(True)
        self.editSignature.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
        self.bold.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
        self.italic.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
        self.underscore.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
        self.font_size.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
        self.fontComboBox.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
        # self.setWindowIcon(Icon("settings").icon)
        Icon("settings", self)
        self.setWindowTitle("Einstellungen")
        self.font_size.setCurrentText("9")
        # add button to toggle password visibility
        if user == "admin":
            self.debug.show()
        else:
            self.debug.hide()
        self.showPassword = True
        self.togglePassword.clicked.connect(self.toggle_password)
        self.toggle_api_visibility.clicked.connect(self.toggle_api)
        self.tb_select_db.clicked.connect(self.select_db)
        self.tb_set_save_path.clicked.connect(self.set_save_path)
        self.bold.clicked.connect(self.setFontBold)
        self.italic.clicked.connect(self.setTextFontItalic)
        self.underscore.clicked.connect(self.setTextFontUnderline)
        self.font_size.currentTextChanged.connect(self.setFontSize)
        self.fontComboBox.currentFontChanged.connect(self.setCurrentFont)
        self.debug.clicked.connect(self.debug_mode)
        self.toggle_password()
        self.toggle_api()
        self.load_config()
        self.buttonBox.accepted.connect(self.save)
        # set text in gridlayout_4 to be not bold

        self.toolBox.setItemIcon(0, Icon("database").icon)
        self.toolBox.setItemIcon(1, Icon("api").icon)
        self.toolBox.setItemIcon(2, Icon("mail").icon)
        self.toolBox.setItemIcon(3, Icon("icons").icon)

        logger.info("Settings dialog opened, data loaded")

    def load_config(self):
        self.db_name.setText(settings.database.name)
        self.db_path.setText(settings.database.path)
        self.save_path.setText(settings.database.temp)
        self.smtp_address.setText(settings.mail.smtp_server)
        self.smtp_port.setText(str(settings.mail.port))
        self.sender_email.setText(settings.mail.sender)
        self.mail_username.setText(settings.mail.user_name)
        self.password.setText(settings.mail.password)
        self.printermail.setText(settings.mail.printer_mail)
        self.printermail.setPlaceholderText("E-Mail-Adresse des Druckers")
        self.use_username_smtp_login.setChecked(
            settings.mail.use_user_name if settings.mail.use_user_name else False
        )
        self.editSignature.setHtml(settings.mail.signature)
        self.zotero_api_key.setText(settings.zotero.api_key)
        self.zotero_library_id.setText(str(settings.zotero.library_id))
        self.zotero_library_type.setText(settings.zotero.library_type)
        for row, color in enumerate(settings.icons.colors):
            # add a label with the color name, a lineedit with the color value and a button to change the color
            label = QtWidgets.QLabel(color)
            lineedit = QtWidgets.QLineEdit(settings.icons.colors[color])
            button = QtWidgets.QPushButton("Farbe ändern")
            button.clicked.connect(lambda: self.change_color(lineedit))
            self.gridLayout_4.addWidget(label, row, 0)
            self.gridLayout_4.addWidget(lineedit, row, 1)
            self.gridLayout_4.addWidget(button, row, 2)
        for i in range(self.gridLayout_4.count()):
            self.gridLayout_4.itemAt(i).widget().setFont(QtGui.QFont("Segoe UI", 9))

        for row, icon in enumerate(settings.icons.icons):
            icon_widget = IconWidget(icon, settings.icons.icons[icon])
            self.vertical_icons.addWidget(icon_widget)

    def change_color(self, lineedit):
        logger.debug("Changing color for {}", lineedit.text())
        colorDialog = QtWidgets.QColorDialog()
        colorDialog.setSizePolicy()
        color = colorDialog.getColor()
        if color.isValid():
            lineedit.setText(color.name())

    def setCurrentFont(self):
        font = self.fontComboBox.currentFont()
        font.setPointSize(int(self.font_size.currentText()))
        self.editSignature.setFont(font)

    def setFontSize(self):
        size = self.font_size.currentText()
        self.editSignature.setFontPointSize(int(size))

    def toggle_password(self):
        # self.togglePassword.setIconSize(QtCore.QSize(16, 16))

        if self.password.echoMode() == QtWidgets.QLineEdit.EchoMode.Password:
            self.password.setEchoMode(QtWidgets.QLineEdit.EchoMode.Normal)

            Icon("show_password", self.togglePassword)
        else:
            self.password.setEchoMode(QtWidgets.QLineEdit.EchoMode.Password)
            Icon("hide_password", self.togglePassword)

    def toggle_api(self):
        if self.zotero_api_key.echoMode() == QtWidgets.QLineEdit.EchoMode.Normal:
            self.zotero_api_key.setEchoMode(QtWidgets.QLineEdit.EchoMode.Password)
            Icon("hide_password", self.toggle_api_visibility)
        else:
            self.zotero_api_key.setEchoMode(QtWidgets.QLineEdit.EchoMode.Normal)
            Icon("show_password", widget=self.toggle_api_visibility)

    def setFontBold(self):
        if self.bold.isChecked():
            self.editSignature.setFontWeight(QtGui.QFont.Weight.Bold)
        else:
            self.editSignature.setFontWeight(QtGui.QFont.Weight.Normal)

    def setTextFontItalic(self):
        if self.italic.isChecked():
            self.editSignature.setFontItalic(True)
        else:
            self.editSignature.setFontItalic(False)

    def setTextFontUnderline(self):
        if self.underscore.isChecked():
            self.editSignature.setFontUnderline(True)
        else:
            self.editSignature.setFontUnderline(False)

    def select_db(self):
        # open file dialog, limit to .db files
        file_dialog = QtWidgets.QFileDialog()
        file_dialog.setFileMode(QtWidgets.QFileDialog.FileMode.AnyFile)
        file_dialog.setNameFilter("Datenbank (*.db)")
        file_dialog.setViewMode(QtWidgets.QFileDialog.ViewMode.Detail)
        if file_dialog.exec():
            self.db_name.setText(file_dialog.selectedFiles()[0].split("/")[-1])
            self.db_path.setText(
                file_dialog.selectedFiles()[0].split(self.db_name.text())[0]
            )

    def set_save_path(self):
        # open file dialog, limit to .db files
        file_dialog = QtWidgets.QFileDialog(filter="Ordner auswählen")
        file_dialog.setFileMode(QtWidgets.QFileDialog.FileMode.Directory)
        file_dialog.setViewMode(QtWidgets.QFileDialog.ViewMode.Detail)
        if file_dialog.exec():
            self.save_path.setText(file_dialog.selectedFiles()[0])

    def debug_mode(self):
        logger.debug(self.editSignature.toHtml())

    def return_data(self):
        port = self.smtp_port.text()
        if port != "None":
            port = int(port)
        else:
            port = 0
        signature = self.editSignature.toHtml()
        if signature != base:
            signature = signature
        else:
            signature = ""
        settings.set_database_attr("name", self.db_name.text())
        settings.set_database_attr("path", self.db_path.text())
        settings.save_path = self.save_path.text()
        settings.set_mail_attr("smtp_server", self.smtp_address.text())
        settings.set_mail_attr("port", port)
        settings.set_mail_attr("sender", self.sender_email.text())
        settings.set_mail_attr("user_name", self.mail_username.text())
        settings.set_mail_attr("password", self.password.text())
        settings.set_mail_attr(
            "use_user_name", self.use_username_smtp_login.isChecked()
        )
        settings.set_mail_attr("printer_mail", self.printermail.text())
        settings.set_mail_attr("signature", signature)
        settings.set_zotero_attr("api_key", self.zotero_api_key.text())
        settings.set_zotero_attr("library_id", self.zotero_library_id.text())
        settings.set_zotero_attr("library_type", self.zotero_library_type.text())

        for color in self.get_colors():
            settings.icons.colors[color] = self.get_colors()[color]
            # print(color)
        for icon in self.get_icons():
            settings.icons.icons[icon] = self.get_icons()[icon]

        return settings

    def get_colors(self) -> dict:
        colors = {}
        for i in range(self.gridLayout_4.count()):
            widget = self.gridLayout_4.itemAt(i).widget()
            if isinstance(widget, QtWidgets.QLineEdit):
                colors[self.gridLayout_4.itemAt(i - 1).widget().text()] = widget.text()
        return colors

    def get_icons(self):
        icons = {}
        for row in range(self.vertical_icons.count()):
            widget = self.vertical_icons.itemAt(row).widget()
            if isinstance(widget, IconWidget):
                data = widget.return_data()
                icons[data[0]] = data[1]
        return icons

    def save(self):
        config = self.return_data()
        # #print(config)

        config.save()
        self.accept()


def launch_settings():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    window = Settings()
    window.show()
    sys.exit(app.exec())
