from axipy import Plugin
from axipy.da import GeometryType
from axipy.gui import view_manager
from axipy.mi import Text
from PySide2.QtCore import Qt
from PySide2.QtWidgets import (
    QCheckBox,
    QLayout,
    QLineEdit,
    QSizePolicy,
    QSpacerItem,
    QVBoxLayout,
    QWidget,
)

from ..data_types import NamedSearchPatterns, SearchPatterns, SearchSettings
from .select_by_style_widget import SelectByStyleWidget
from .style_widget_interface import SelectByStyleWidgetInterface


class TextWidget(SelectByStyleWidgetInterface):

    def __init__(self, text: str, property_widget: "SelectByStyleWidget", parent: QWidget) -> None:
        super().__init__(parent)
        self.__property = property_widget
        self.__text_edit = QLineEdit(text, self)
        self.__text_property_key = "text_property_key"
        layout = QVBoxLayout(self)
        layout.setContentsMargins(3, 3, 3, 3)
        layout.setSpacing(0)
        layout.addWidget(self.__property)
        layout.addWidget(self.__text_edit)
        layout.addSpacerItem(QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding))
        self.setLayout(layout)

    def result(self) -> SearchSettings:
        return SearchSettings({self.text_property_key: self.search_patterns}, {GeometryType.Text: True})

    @staticmethod
    def text_key() -> str:
        return "TextWidget_text_key"

    @property
    def text_property_key(self) -> str:
        return self.__text_property_key

    @text_property_key.setter
    def text_property_key(self, key: str):
        self.__text_property_key = key

    @property
    def search_patterns(self) -> SearchPatterns:
        properties = self.__property.result()
        assert len(properties.groups)
        # точно известно что внутри только одна группа
        search_patterns = properties.groups[self.__text_property_key]
        search_patterns[self.text_key()] = self.__text_edit.text()
        return search_patterns

    @search_patterns.setter
    def search_patterns(self, patterns: SearchPatterns):
        self.__property.search_patterns = NamedSearchPatterns(patterns, self.__text_property_key)

    def fill_layout(self, patterns: NamedSearchPatterns, layout: QLayout):
        if patterns.name not in self.__patterns_comboboxes:
            self.__patterns_comboboxes[patterns.name] = {}
        grouped_comboboxes = self.__patterns_comboboxes[patterns.name]
        for pattern_name, is_checked in patterns.patterns.items():
            cb = QCheckBox(pattern_name)
            cb.setCheckState(Qt.Checked if is_checked else Qt.Unchecked)
            layout.addWidget(cb)
            grouped_comboboxes[pattern_name] = cb

    @staticmethod
    def make_text_widget(iface: Plugin, geometry: Text, parent: QWidget = None) -> "TextWidget":
        property_widget = SelectByStyleWidget(view_manager.global_parent, iface)
        return TextWidget(geometry.text, property_widget, parent)
