import os

from qgis.core import Qgis, QgsExpressionContextUtils, QgsProject, QgsProviderRegistry
from qgis.PyQt import QtCore
from qgis.PyQt.QtWidgets import QDialog, QDialogButtonBox, QListWidget, QVBoxLayout
from qgis.utils import iface

from folios_wizard.qt_utils import tr

folio_variables = [
    "folio_layout_name",
    "folio_print_scale",
    "folio_text_scale",
    "folio_title",
    "folio_subtitle",
    "folio_map_name",
    "folio_description",
    "folio_field1",
    "folio_field2",
    "folio_field3",
    "folio_field4",
]


def clean_project_variables():
    # for key in meta_variables:
    for key in QgsExpressionContextUtils.projectScope(
        QgsProject.instance()
    ).variableNames():
        if key.startswith("metadata_"):
            try:
                QgsExpressionContextUtils.removeProjectVariable(
                    QgsProject.instance(), key
                )
            except Exception:
                pass

    for key in folio_variables:
        try:
            QgsExpressionContextUtils.removeProjectVariable(QgsProject.instance(), key)
        except Exception:
            pass


def read_show_metadata(show_details: bool = False, verbose: bool = False):
    try:
        clean_project_variables()
        message = QListWidget()
        to_show = False
        gpkg = os.path.basename(QgsProject.instance().fileName()).replace(
            ".qgs", ".gpkg"
        )
        new_gpkg = f"{QgsProject.instance().homePath()}/data/{gpkg}"
        md = QgsProviderRegistry.instance().providerMetadata("ogr")
        conn = md.createConnection(new_gpkg, {})
        result = conn.executeSql("SELECT * FROM metadata ORDER BY fid")
        for row in result:
            text_content = f"{row[1]} : {row[2]}"
            QgsExpressionContextUtils.setProjectVariable(
                QgsProject.instance(), f"metadata_{row[1].lower()}", row[2]
            )
            message.addItem(text_content)
            if show_details:
                to_show = True

        md.disconnect()

        if to_show:
            message.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
            message.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
            message.setFixedSize(
                message.sizeHintForColumn(0) + 2 * message.frameWidth(),
                message.sizeHintForRow(0) * message.count() + 2 * message.frameWidth(),
            )
            dlg = QDialog(iface.mainWindow())
            dlg.setModal(True)
            dlg.setWindowTitle(tr("Project details"))
            QBtn = QDialogButtonBox.Ok
            dlg.buttonBox = QDialogButtonBox(QBtn)
            dlg.buttonBox.accepted.connect(dlg.accept)
            layout = QVBoxLayout()
            layout.addWidget(message)
            layout.addWidget(dlg.buttonBox)
            dlg.setLayout(layout)
            dlg.show()
    except Exception as e:
        if verbose:
            msgbar = iface.messageBar()
            msgbar.pushMessage("openproject: ", str(e), Qgis.Warning, 5)


def saveProject():
    pass


def closeProject():
    pass
