# 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
import os
from tempfile import gettempdir

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

from .get_output_file_name import GetOutputFileName

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


class NewProjectDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, iface, parent=None):
        super(NewProjectDialog, self).__init__(parent)
        self.iface = iface
        frm1 = QHBoxLayout()
        clabel = QLabel()
        clabel.setText("Select projection")
        frm1.addWidget(clabel)

        self.srid_chooser = QgsProjectionSelectionWidget()
        self.srid_chooser.setMinimumWidth(250)
        frm1.addWidget(self.srid_chooser)

        self.but = QPushButton()
        self.but.clicked.connect(self.create)
        self.but.setText("Create")
        frm1.addWidget(self.but)
        self.project_name = None

        self.setLayout(frm1)
        self.resize(500, 60)

    def create(self):
        proj = self.srid_chooser.crs()

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

        if self.project_name is None:
            self.__get_name()

        Network().create(self.project_name, int(proj.authid().split(":")[1]), True)

        self.close()

    def __get_name(self):
        self.project_name, _ = GetOutputFileName(
            QtWidgets.QDialog(), "New Polaris Supply file", ["Polaris network (*.sqlite)"], ".sqlite", gettempdir()
        )
