"""
/***************************************************************************
 DlgUtil
                                 A QGIS plugin
 Dialog utils
        begin                : 2022-12-04
        copyright            : (C) 2022 by Jean-Marie Arsac
        email                : jmarsac@azimut.fr
 ***************************************************************************/

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

from qgis.PyQt import QtWidgets
from qgis.PyQt.QtCore import QCoreApplication, QDate, Qt, QVariant
from qgis.PyQt.QtWidgets import QFileDialog, QMessageBox

from topaze.toolbelt.i18n import tr


class DlgUtil:
    def __init__(self, service_name):
        ...

    @staticmethod
    def load_listwidget_array(lw, string_array: [], add_empty: bool = False):
        if add_empty:
            lw.addItem("")
        for s in string_array:
            lw.addItem(s)

    @staticmethod
    def load_combobox_list(cbox, query, sql_string, add_empty: bool = True):
        cbox.clear()
        if add_empty:
            cbox.addItem("")
        if query and sql_string:
            if query.exec(sql_string):
                while query.next():
                    cbox.addItem(str(query.value(0)))
            else:
                print(query.lastError())

    @staticmethod
    def load_combobox_list_array(cbox, string_array: [], add_empty: bool = True):
        cbox.clear()
        if add_empty:
            cbox.addItem("")
        for s in string_array:
            cbox.addItem(s)

    @staticmethod
    def update_lineedit_with_value(widget_item, value):
        try:
            if not ((isinstance(value, QVariant) and value.isNull()) or value is None):
                if isinstance(value, int):
                    widget_item.setText(str(value))
                else:
                    widget_item.setText(value)
            else:
                widget_item.clear()
        except Exception as e:
            print(f"Type : {type(value)}, value : {value} Error {str(e)}")

    @staticmethod
    def update_checkbox_with_value(widget_item, value):
        try:
            if not ((isinstance(value, QVariant) and value.isNull()) or value is None):
                if (
                    str(value).lower() == tr("yes")
                    or str(value).lower() == tr("true")
                    or value == tr("y")
                    or value == "t"
                    or value == tr("on")
                ):
                    widget_item.setCheckState(Qt.Checked)
                else:
                    widget_item.setCheckState(Qt.Unchecked)
        except Exception as e:
            print(f"Type : {type(value)}, value : {value} Error {str(e)}")

    @staticmethod
    def update_combobox_with_value(widget_item, value):
        try:
            if not ((isinstance(value, QVariant) and value.isNull()) or value is None):
                widget_item.setCurrentText(value)
        except Exception as e:
            print(f"Type : {type(value)}, value : {value} Error {str(e)}")

    @staticmethod
    def update_textedit_with_value(widget_item, value):
        try:
            if not ((isinstance(value, QVariant) and value.isNull()) or value is None):
                if isinstance(value, int):
                    widget_item.setText(str(value))
                else:
                    widget_item.setText(value)
            else:
                widget_item.clear()
        except Exception as e:
            print(f"Type : {type(value)}, value : {value} {str(e)}")

    @staticmethod
    def update_timeedit_with_value(widget_item, value):
        try:
            if not ((isinstance(value, QVariant) and value.isNull()) or value is None):
                widget_item.setTime(value)
        except Exception as e:
            print(f"Type : {type(value)}, value : {value} {str(e)}")

    @staticmethod
    def update_dateedit_with_value(widget_item, value):
        try:
            if not ((isinstance(value, QVariant) and value.isNull()) or value is None):
                widget_item.setDate(value)
            else:
                widget_item.setDate(QDate(1900, 1, 1))
        except Exception as e:
            print(f"Type : {type(value)}, value : {value} {str(e)}")

    @staticmethod
    def prepare_lineedit_value(value):
        print(type(value))
        if value is not None:
            if isinstance(value, QDate):
                if value.isNull():
                    sdat = ""
                else:
                    sdat = f"{value.day():02d}/{value.month():02d}/{value.year():02d}"
                return sdat
            else:
                if value:
                    return str(value)
                else:
                    return ""
        else:
            return ""
        ...

    @staticmethod
    def str_date_iso_to_french(dat):
        if len(dat) == 8:
            return f"{dat[6:8]}/{dat[4:6]}/{dat[0:4]}"
        elif len(dat) == 10:
            return f"{dat[8:10]}/{dat[5:7]}/{dat[0:4]}"
        else:
            return ""

    @classmethod
    def showDialogConfig(
        self,
        obj,
        flag: str = "Directory",
        prompt: str = "",
        start_dir: str = "",
        filter: str = "",
    ):
        if flag == "File":
            if prompt:
                fname, _ = QFileDialog.getOpenFileName(None, prompt, start_dir, filter)
            else:
                fname, _ = QFileDialog.getOpenFileName(
                    self,
                    tr("Select file"),
                    start_dir,
                    tr("All files (*.*)"),
                )
        else:
            if prompt:
                fname = QFileDialog.getExistingDirectory(self, prompt)
            else:
                fname = QFileDialog.getExistingDirectory(self, tr("Select a folder"))

        if fname:
            obj.setText(fname)

    @staticmethod
    def show_alert(
        title,
        msg,
        button_yes: QMessageBox.StandardButton = QMessageBox.Yes,
        button_no: QMessageBox.StandardButton = QMessageBox.No,
    ):
        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setText(msg)
        msgBox.setWindowTitle(title)
        msgBox.setStandardButtons(button_yes | button_no)
        # msgBox.buttonClicked.connect(msgButtonClick)
        returnValue = msgBox.exec()
        if returnValue == button_yes:
            return True
        else:
            return False

    @staticmethod
    def show_message_box(
        msg: str = "", typ: str = "information", title: str = "Information"
    ):
        if msg:
            msg_box = QtWidgets.QMessageBox()
            if typ.lower() == "critical":
                msg_box.setIcon(QtWidgets.QMessageBox.Critical)
            elif typ.lower() == "warning":
                msg_box.setIcon(QtWidgets.QMessageBox.Warning)
            else:
                msg_box.setIcon(QtWidgets.QMessageBox.Information)
            msg_box.setText(msg)
            msg_box.setWindowTitle(title)
            msg_box.setStandardButtons(QtWidgets.QMessageBox.Ok)
            msg_box.exec()
