from typing import TYPE_CHECKING

from console_base.api.serializers import LCModelSerializer
from console_base.api.viewsets import LCModelViewSet
from ..signals import record_saved_via_umbrella_api

if TYPE_CHECKING:
    SignalsMixinBase = LCModelViewSet
else:
    SignalsMixinBase = object


class RecordSavedViaUmbrellaApi(SignalsMixinBase):
    """
    Records can be created / updated via Umbrella Users,
    authenticated with signed Paseto tokens.

    Send signals on such events, with the AccessToken
    attached, so that further actions can be taken on
    the basis of the AccessToken payload or footer.
    """

    def perform_create(self, serializer: LCModelSerializer) -> None:
        super().perform_create(serializer)
        self.send_umbrella_api_signal(serializer, True)

    def perform_update(self, serializer: LCModelSerializer) -> None:
        super().perform_update(serializer)
        self.send_umbrella_api_signal(serializer, False)

    def send_umbrella_api_signal(self, serializer: LCModelSerializer, created: bool) -> None:
        try:
            record_saved_via_umbrella_api.send(
                sender=serializer.Meta.model,
                access_token=self.request.access_token,
                serializer_data=serializer.data,
                created=created,
            )
        except AttributeError:
            pass
