# 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 polaris.analyze.mapping.flow_lines import delaunay_assignment, desire_lines
from polaris.analyze.trip_metrics import TripMetrics
from polaris.utils.database.data_table_access import DataTableAccess
from polaris.utils.database.db_utils import read_and_close, has_table
from qgis.PyQt.QtCore import QTime
from qgis.PyQt.QtGui import QFont
from qgis.PyQt.QtWidgets import QApplication
from qgis.PyQt.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QComboBox, QLabel, QDialog, QTimeEdit, QPushButton
from qgis.core import QgsLineSymbol, QgsSimpleLineSymbolLayer
from qgis.utils import iface

from QPolaris.modules.common_tools import GetOutputFileName
from QPolaris.modules.common_tools.common_matrix_extraction import CommonMatrixExtractionDialog


class ExportMatricesDialog(CommonMatrixExtractionDialog):
    def __init__(self, _PQgis):
        super().__init__(_PQgis)
        self.complete_ui()
        self.__data = {}
        self._output = None

    def complete_ui(self):
        # Main layout
        self.setFixedSize(560, 180)

        # Execution button name and action
        self.go.setText("Export matrices")
        self.go.clicked.connect(self.load_data)

        self.setWindowTitle("Export vehicle matrices to OMX")

    def load_data(self):
        if self._output is None:
            self._output, _ = GetOutputFileName(
                QDialog(), "Matrix export", ["Open Matrix (*.omx)"], ".omx", self.project.path
            )
            if self._output is None:
                return

        self.go.setEnabled(False)
        trip_metrics = TripMetrics(self.project.supply_path, self.project.demand_path)

        # Let's get all the trips for the last iteration
        fromtime = int(self.from_time.time().hour() * 3600 + self.from_time.time().minute() * 60)
        totime = int(self.to_time.time().hour() * 3600 + self.to_time.time().minute() * 60)
        agg = self.aggregation.currentText().lower()
        matrix = trip_metrics.trip_matrix(from_start_time=fromtime, to_start_time=totime, aggregation=agg)

        matrix.to_aeq().export(self._output)
        self.close()
