# Copyright (c) 2025, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2025, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
from os import PathLike
from os.path import dirname, join
from polaris.network.utils.worker_thread import WorkerThread
from polaris.utils.database.database_dumper import dump_database_to_csv
from polaris.utils.database.db_utils import read_and_close
from polaris.utils.signals import SIGNAL
from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QDialog

FORM_CLASS, _ = uic.loadUiType(join(dirname(dirname(__file__)), "common_tools/forms/progress.ui"))


class DumpDialog(QDialog, FORM_CLASS):
    def __init__(self, _PQgis, folder):
        QDialog.__init__(self)
        self.iface = _PQgis.iface
        self.finished = False

        self.setupUi(self)
        self._PQgis = _PQgis
        self.srid = -1
        self.worker_thread = NetworkDumper(folder, _PQgis.supply_path)
        self.dump()

    def dump(self):
        self.worker_thread.dumping.connect(self.signal_handler)
        self.worker_thread.run()

    def signal_handler(self, val):
        if val[0] == "start":
            self.setWindowTitle("Dumping Network to flat files")
            self.lbl_progress.setText(val[3])
            self.progressBar.setRange(0, val[2])
            self.progressBar.setValue(0)
        elif val[0] == "update":
            self.progressBar.setValue(val[2])
            self.lbl_progress.setText(val[3])
        elif val[0] == "finished_dumping_procedure":
            self.lbl_progress.setText("FINISHED")
            self.finished = True
            self.close()

    def closeEvent(self, event):
        event.accept()


# This is used by QGIS, so we need to keep it in the network module
class NetworkDumper(WorkerThread):
    dumping = SIGNAL(object)

    def __init__(self, folder_name: str, path_to_file: PathLike):
        WorkerThread.__init__(self, None)
        self.folder_name = folder_name
        self.path_to_file = path_to_file

    def doWork(self):
        """Alias for execute"""
        with read_and_close(self.path_to_file, spatial=True) as conn:
            dump_database_to_csv(conn, self.folder_name, self.dumping)
