# 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
# Copied directly from the AequilibraE plugin
from os.path import dirname, join
from tempfile import gettempdir

from polaris.network.network import Network
from polaris.network.ie.import_export import ImportExport
from qgis.core import QgsUnitTypes
from qgis.gui import QgsProjectionSelectionWidget
from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout

from ..common_tools import GetOutputFileName, GetOutputFolderName

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


class ImportGMNSDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, iface, parent=None):
        super(ImportGMNSDialog, self).__init__(parent)
        self.iface = iface

        self.gmns_path = None
        self.output_file = None
        main_layout = QVBoxLayout()

        # CRS selection Boxes
        self.gmns_srid = QgsProjectionSelectionWidget()
        self.model_srid = QgsProjectionSelectionWidget()

        for crswidget, label in [[self.gmns_srid, "GMNS original"], [self.model_srid, "Desired model"]]:
            frm1 = QHBoxLayout()
            clabel = QLabel(text=f"{label} projection")
            clabel.setMinimumWidth(140)
            frm1.addWidget(clabel)

            crswidget.setMinimumWidth(250)
            crswidget.crsChanged.connect(self.set_all_valid)

            frm1.addWidget(crswidget)
            main_layout.addItem(frm1)

        frm1 = QHBoxLayout()
        self.__gmns_path = QLabel(text="")
        self.__gmns_path.setMinimumWidth(200)
        self.choose_gmns = QPushButton(text="Select GMNS")
        self.choose_gmns.clicked.connect(self.select_source)
        self.choose_gmns.setMaximumWidth(90)
        frm1.addWidget(self.choose_gmns)
        frm1.addWidget(self.__gmns_path)
        main_layout.addItem(frm1)

        self.but = QPushButton(text="Create from GMNS")
        self.but.clicked.connect(self.create)
        main_layout.addWidget(self.but)

        self.setLayout(main_layout)
        self.resize(500, 60)
        self.set_all_valid()

    def select_source(self):
        self.gmns_path = self.gmns_path or GetOutputFolderName("", message="Location of GMNS files") or self.gmns_path
        self.__gmns_path.setText("")
        if self.gmns_path:
            self.__gmns_path.setText(self.gmns_path)

        self.set_all_valid()

    def set_all_valid(self):
        self.but.setEnabled(False)
        if not self.gmns_path:
            return

        if min(self.gmns_srid.crs().bounds().width(), self.gmns_srid.crs().bounds().height()) == 0:
            return

        if min(self.model_srid.crs().bounds().width(), self.model_srid.crs().bounds().height()) == 0:
            return

        self.but.setEnabled(True)

    def create(self):
        if not self.output_file:
            self.output_file, _ = GetOutputFileName(
                QtWidgets.QDialog(), "New Polaris Supply file", ["Polaris network (*.sqlite)"], ".sqlite", gettempdir()
            )
            if not self.output_file:
                return

        gmns_srid = self.gmns_srid.crs()
        model_srid = self.model_srid.crs()

        if model_srid.mapUnits() != QgsUnitTypes().DistanceMeters:
            self.iface.messageBar().pushMessage(
                "Error", "Model projection should have meters as unit", level=3, duration=10
            )
            return

        Network().create(self.output_file, int(model_srid.authid().split(":")[1]), True)
        ie = ImportExport(self.output_file)
        ie.from_gmns(self.gmns_path, str(gmns_srid.authid()))
        self.close()
