import configparser
import itertools

from axipy import ActionButton, Position, Plugin, view_manager

from .dialog import Dialog


class PenConverter(Plugin):

    def __init__(self):
        self._button = ActionButton(
            title=self.tr("Стиль\nлиний"),
            on_click=self.on_click,
            icon="://icons/share/32px/run3.png"
        )
        position = Position(self.tr("Основные"), self.tr("Команды"))
        position.add(self._button)

    @property
    def name(self) -> str:
        config_parser = configparser.ConfigParser()

        file_path = self.plugin_dir / "manifest.ini"

        try:
            config_parser.read(file_path, "UTF-8")
        except configparser.MissingSectionHeaderError:
            with open(file_path, encoding="UTF-8") as lines:
                lines = itertools.chain(
                    ("[general]",),
                    lines,
                )
                config_parser.read_file(lines)

        return config_parser["general"]["name"]

    def unload(self):
        self._button.remove()

    @staticmethod
    def on_click():
        w = Dialog(parent=view_manager.global_parent)
        w.open()
