"""
lochraster_plugin.py
ActionPlugin-Einstiegspunkt für den Lochraster-Generator.
"""

import os
import traceback

import pcbnew
import wx

from lochraster_dialog import LochrasterDialog
from lochraster_core import LochrasterGenerator


class LochrasterPlugin(pcbnew.ActionPlugin):

    def defaults(self):
        self.name = "Lochraster Generator"
        self.category = "PCB Layout"
        self.description = (
            "Erzeugt ein Lochraster-Layout (2,54 mm Raster) mit "
            "wahlweise einzelnen Vias oder Kupferstreifen, "
            "ein- oder zweiseitig."
        )
        self.show_toolbar_button = True
        icon = os.path.join(os.path.dirname(__file__), "icon.png")
        if os.path.isfile(icon):
            self.icon_file_name = icon

    def Run(self):
        board = pcbnew.GetBoard()
        if board is None:
            wx.MessageBox(
                "Kein Board geöffnet.", "Lochraster Generator",
                wx.OK | wx.ICON_ERROR
            )
            return

        try:
            dlg = LochrasterDialog(None)
            if dlg.ShowModal() == wx.ID_OK:
                settings = dlg.get_settings()
                gen = LochrasterGenerator(board, settings)
                gen.generate()
                wx.MessageBox(
                    f"Lochraster erzeugt: {settings['cols']} × {settings['rows']} Punkte.",
                    "Lochraster Generator",
                    wx.OK | wx.ICON_INFORMATION,
                )
        except Exception:
            wx.MessageBox(
                f"Fehler:\n{traceback.format_exc()}",
                "Lochraster Generator",
                wx.OK | wx.ICON_ERROR,
            )
        finally:
            dlg.Destroy()
