from dataclasses import dataclass

from clochette.application.store.CalendarConfigurationStore import CalendarConfigurationStore
from clochette.application.usecase.calendar.DeleteCalendarUseCase import DeleteCalendarUseCase
from clochette.framework.qt.Link import LightLink
from clochette.framework.qt.QComponent import QComponent
from clochette.presentation.settings.calendar.CalendarNavigationModel import CalendarNavigationModel
from clochette.presentation.settings.calendar.list.QCalendarListView import QCalendarListView


@dataclass
class QCalendarListComponent(QComponent[QCalendarListView]):
    """Component that wires calendar store, navigation, and use cases to the list view"""

    _view: QCalendarListView
    _calendar_configuration_store: CalendarConfigurationStore
    _calendar_navigation_model: CalendarNavigationModel
    _delete_calendar_usecase: DeleteCalendarUseCase

    def __post_init__(self):
        super().__init__(self._view)

        # Wire store to view - set_calendars is already thread-safe via InSolidSignal
        LightLink(
            observable=self._calendar_configuration_store.calendars,
            handler=self._view.set_calendars,
            widget=self._view,
        )

        # Wire view events to navigation and use cases
        self._view.on_add_clicked.link(self._on_add_clicked)
        self._view.on_edit_clicked.link(self._on_edit_clicked)
        self._view.on_delete_clicked.link(self._on_delete_clicked)

    def _on_add_clicked(self):
        """Handle add button click"""
        self._calendar_navigation_model.add_calendar.on_next(True)

    def _on_edit_clicked(self):
        """Handle edit button click"""
        calendar = self._view.selected_calendar
        if calendar is not None:
            self._calendar_navigation_model.edit_calendar.on_next(calendar)

    def _on_delete_clicked(self):
        """Handle delete button click"""
        calendar = self._view.selected_calendar
        if calendar is not None:
            self._delete_calendar_usecase.delete_calendar(calendar).subscribe()
