# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
from os.path import dirname, join

from qgis.gui import QgsProjectionSelectionWidget
from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout

from ..common_tools import GetOutputFolderName

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


class ExportGMNSDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, proj, parent=None):
        super(ExportGMNSDialog, self).__init__(parent)
        self.iface = proj.iface
        self.ie = proj.network.ie
        self.gmns_path = None
        self.gmns_path = None
        main_layout = QVBoxLayout()

        # CRS selection Boxes
        self.gmns_srid = QgsProjectionSelectionWidget()

        frm1 = QHBoxLayout()
        clabel = QLabel(text="Output projection")
        clabel.setMinimumWidth(140)
        frm1.addWidget(clabel)

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

        frm1.addWidget(self.gmns_srid)
        main_layout.addItem(frm1)

        frm1 = QHBoxLayout()
        self.__gmns_path = QLabel(text="")
        self.__gmns_path.setMinimumWidth(200)
        frm1.addWidget(self.__gmns_path)
        main_layout.addItem(frm1)

        self.but = QPushButton(text="Export to GMNS")
        self.but.clicked.connect(self.export_gmns)
        main_layout.addWidget(self.but)

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

    def set_all_valid(self):
        self.but.setEnabled(False)
        if min(self.gmns_srid.crs().bounds().width(), self.gmns_srid.crs().bounds().height()) == 0:
            return
        self.but.setEnabled(True)

    def export_gmns(self):
        if not self.gmns_path:
            self.gmns_path = GetOutputFolderName("", message="Target for GMNS files")

        gmns_srid = self.gmns_srid.crs().authid().split(":")[1]

        self.ie.to_gmns(self.gmns_path, f"epsg:{gmns_srid}")
        self.close()
