import os
from pathlib import Path
from typing import Optional

import axipy
from PySide2.QtCore import Qt, QFileInfo
from PySide2.QtUiTools import QUiLoader
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import QDialog, QFileDialog, QDialogButtonBox
from axipy.app import Version


from axipy import view_manager, data_manager, Plugin, mainwindow


class SavePointsDialog(QDialog):

    def __init__(self, iface: Plugin) -> None:
        if Version.compare(6,2) == -1:
            super().__init__(mainwindow.widget)
        else:
            super().__init__(mainwindow.qt_object())
        self._tr = iface.tr
        ui_file = os.path.join(os.path.dirname(__file__), "SavePointsDialog.ui")
        self._ui = QUiLoader().load(ui_file, self)
        self._file_name = None
        self._load_ui()
        self._ui.setParent(view_manager.global_parent)
        self._ui.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        self._ui.cbRound.stateChanged.connect(self.__cbRound_state_changed)

    def __cbRound_state_changed(self, state: int) -> None:
        self._ui.sbPrecision.setEnabled(state)

    def _load_ui(self) -> None:
        for t in data_manager.tables:
            self._ui.cbTables.addItem(t.name)
        self._ui.buttonBox.button(QDialogButtonBox.Ok).setEnabled(self._ui.cbTables.count())
        self._ui.setWindowIcon(QIcon(os.path.join(os.path.dirname(__file__), 'save.png')))

    def _select_file(self) -> Optional[str]:
        if Version.compare(6,2) == -1:
            result: Optional[Path] = axipy.save_file_dialog(
                filter_arg=self._tr("Таблицы Excel (*.xlsx);;CSV файлы (*.csv);;MapInfo TAB (*.tab)"),
                title=self._tr("Сохранить как узлы" ),
            )
        else:
            result: Optional[Path] = axipy.save_file_dialog(
                filter_arg=self._tr("Таблицы Excel (*.xlsx);;CSV файлы (*.csv);;MapInfo TAB (*.tab)")
            )
        if result:
            return str(result)

    def result_file_name(self) -> str:
        return self._file_name

    def result_table(self) -> str:
        # Результирующая базовая таблица
        return data_manager.find(self._ui.cbTables.currentText())

    def result_format_data_index(self) -> int:
        return self._ui.cbFormatData.currentIndex()

    def result_type_coordinates_index(self) -> int:
        return self._ui.cbTypeData.currentIndex()

    def result_precision(self) -> Optional[int]:
        if self._ui.cbRound.checkState() == Qt.Checked:
            return self._ui.sbPrecision.value()
        return None

    def accept(self) -> None:
        super().accept()

    def exec(self) -> QDialog.DialogCode:
        res = self._ui.exec()
        if res == QDialog.Accepted:
            self._file_name = self._select_file()
        return QDialog.Accepted if res == QDialog.Accepted and self._file_name is not None else QDialog.Rejected
