from pathlib import Path

from qgis.PyQt import QtCore, QtWidgets, QtGui

from .ui_version_dialog import Ui_TuflowVersionManager
from .available_versions import AvailableVersionsMixin
from .locations import BinaryLocationsMixin
from .help import HelpMixin


ICON_DIR = Path(__file__).parents[1] / 'icons'


class TuflowVersionDialog(QtWidgets.QDialog, Ui_TuflowVersionManager, AvailableVersionsMixin, BinaryLocationsMixin, HelpMixin):

    def __init__(self, parent = None):
        super().__init__(parent)
        self.setupUi(self)
        self.pages = []

        # get the dialog state
        dlg_state = QtCore.QSettings().value('tuflow_plugin/tfversion_dialog/state', None)
        if dlg_state is not None:
            self.restoreGeometry(dlg_state)

        # get the splitter state
        splitter_state = QtCore.QSettings().value('tuflow_plugin/tfversion_dialog/splitter_state', None)
        if splitter_state is not None:
            self.splitter.restoreState(splitter_state)
        else:
            self.splitter.setSizes([100, 350])
        self.splitter.splitterMoved.connect(self.splitter_moved)

        self.tree_model = QtGui.QStandardItemModel(self)
        self.tree_model.appendRow(self.create_item('Versions', self.icon('console.svg')))
        self.tree_model.appendRow(self.create_item('Locations', self.icon('folder.svg')))
        self.tree_model.appendRow(self.create_item('Help', self.icon('help-square.svg')))

        self.pages.append(self._init_available_versions(self.page_layout))
        self.pages.append(self._init_binary_locations(self.page_layout))
        self.pages.append(self._init_help(self.page_layout))

        self.options_tree_view.setModel(self.tree_model)
        self.options_tree_view.header().hide()
        idx = QtCore.QSettings().value('tuflow_plugin/tfversion_dialog/last_index', 0, type=int)
        self.options_tree_view.setCurrentIndex(self.tree_model.index(idx, 0))
        self.current_page = self.get_page_from_index(self.tree_model.index(idx, 0))
        self.current_page.show()

        self.options_tree_view.selectionModel().selectionChanged.connect(lambda x, y: self.index_changed(x, y))

        self.folders_changed.connect(self.refresh_available_versions)
        self.bins_changed.connect(self.refresh_available_versions)

    @staticmethod
    def icon(name: str) -> QtGui.QIcon:
        icon_path = ICON_DIR / name
        if icon_path.exists():
            return QtGui.QIcon(str(icon_path))
        return QtGui.QIcon()

    def create_item(self, name: str, icon: QtGui.QIcon = None):
        if icon:
            return QtGui.QStandardItem(icon, name)
        return QtGui.QStandardItem(name)

    def resizeEvent(self, event: QtGui.QResizeEvent):
        super().resizeEvent(event)
        QtCore.QSettings().setValue('tuflow_plugin/tfversion_dialog/state', self.saveGeometry())

    def moveEvent(self, event: QtGui.QMoveEvent):
        super().moveEvent(event)
        QtCore.QSettings().setValue('tuflow_plugin/tfversion_dialog/state', self.saveGeometry())

    def splitter_moved(self, pos: int, index: int):
        QtCore.QSettings().setValue('tuflow_plugin/tfversion_dialog/splitter_state', self.splitter.saveState())

    def get_page_from_index(self, index: QtCore.QModelIndex) -> QtWidgets.QBoxLayout:
        return self.pages[index.row()]

    def index_changed(self, selected: QtCore.QItemSelection, deselected: QtCore.QItemSelection):
        self.current_page.hide()
        for index in selected.indexes():
            self.current_page = self.get_page_from_index(index)
            self.current_page.show()
            QtCore.QSettings().setValue('tuflow_plugin/tfversion_dialog/last_index', index.row())
            break
