from typing import TYPE_CHECKING, Final

import axipy
from PySide2.QtCore import Slot
from PySide2.QtWidgets import QDialog

from .ui.ui_dialog import Ui_Dialog
from .utils import Direction
from .worker import ContoursDirectionCalculator, Worker

if TYPE_CHECKING:
    from ...__init__ import CadTools

__all__ = [
    "Dialog",
]

title: Final[str] = "Изменить направление контуров"


class Dialog(QDialog, Ui_Dialog):

    def __init__(self, plugin: "CadTools", *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.setupUi(self)

        for cbox in (self.cbox_contours_direction_outer, self.cbox_contours_direction_inner):
            cbox.insertItem(Direction.CLOCKWISE, plugin.tr("По часовой"))
            cbox.insertItem(Direction.COUNTERCLOCKWISE, plugin.tr("Против часовой"))

        selection_table = axipy.data_manager.selection
        if selection_table is None:
            axipy.show_dialog(
                title="Проверка таблицы выборки",
                text="Таблица выборки отсутствует.",
                icon=axipy.DlgIcon.ERROR,
            )
            raise RuntimeError("Missing selection table.")
        calc = ContoursDirectionCalculator()
        outer_contours_direction, holes_exist, inner_contours_direction = calc.run_and_get(selection_table)
        self.outer_contours_direction_calc: Direction = outer_contours_direction
        self.holes_exist: bool = holes_exist
        self.inner_contours_direction_calc: Direction = inner_contours_direction

        self.cbox_contours_direction_outer.setCurrentIndex(outer_contours_direction)

        if not holes_exist:
            self.cbox_contours_direction_inner.setCurrentIndex(-1)
            self.cbox_contours_direction_inner.setEnabled(False)
        else:
            self.cbox_contours_direction_inner.setCurrentIndex(inner_contours_direction)

        self.cbox_outer_starting_index: int = self.cbox_contours_direction_outer.currentIndex()
        self.cbox_inner_starting_index: int = self.cbox_contours_direction_inner.currentIndex()

        self.cbox_contours_direction_outer.currentIndexChanged.connect(self.slot_check_accept_enabled)
        self.cbox_contours_direction_inner.currentIndexChanged.connect(self.slot_check_accept_enabled)

        self.buttonBox.button(self.buttonBox.Ok).setText("Изменить")
        self.buttonBox.button(self.buttonBox.Ok).setEnabled(False)

    @Slot()
    def slot_check_accept_enabled(self) -> None:
        enabled: bool = (self.cbox_outer_starting_index != self.cbox_contours_direction_outer.currentIndex()) or (
            self.cbox_inner_starting_index != self.cbox_contours_direction_inner.currentIndex()
        )
        self.buttonBox.button(self.buttonBox.Ok).setEnabled(enabled)

    def done(self, return_code: int) -> None:
        if return_code == self.Accepted:
            outer_i = self.cbox_contours_direction_outer.currentIndex()
            inner_i = self.cbox_contours_direction_inner.currentIndex()
            worker = Worker(self.outer_contours_direction_calc, self.inner_contours_direction_calc)
            dt = axipy.DialogTask(worker.change_direction, cancelable=True)
            count, len_ids = dt.run_and_get(Direction(outer_i), self.holes_exist, Direction(inner_i))
            if len_ids > 0:
                n_type = axipy.Notifications.Success
            else:
                n_type = axipy.Notifications.Warning
            axipy.Notifications.push(
                title,
                f"Изменено записей: {len_ids}/{count}",
                n_type,
            )
        super().done(return_code)
