import json
from dataclasses import dataclass

from clochette.application.repository.CalendarAuthenticationRepository import CalendarAuthenticationRepository
from clochette.application.service.provider.dto.IKeyringService import IKeyringService
from clochette.domain.entity.CalendarID import CalendarID
from clochette.provider.basic.dto.BasicCredentials import BasicCredentials


@dataclass
class BasicAuthenticationService(IKeyringService[BasicCredentials]):
    _calendar_authentication_repository: CalendarAuthenticationRepository

    def store_auth(self, calendar_id: CalendarID, auth: BasicCredentials) -> None:
        self._calendar_authentication_repository.store_value(calendar_id, json.dumps(auth, default=vars))

    def retrieve_auth(self, calendar_id: CalendarID) -> BasicCredentials | None:
        value = self._calendar_authentication_repository.get_value(calendar_id)
        if value:
            json_value = json.loads(value)
            return BasicCredentials(json_value.get("username"), json_value.get("password"))

        return None
