import json
from datetime import date
from typing import (
    List,
    Optional,
)

from ._S3Config import S3Config


class Boto3ProcessedDaysRepository(object):
    def __init__(
        self,
        s3_client,
        s3_config: S3Config,
    ):
        self.s3_config = s3_config
        self.s3_client = s3_client
        self.bucket_name = s3_config.bucket_name
        self.control_file_path = f"{s3_config.context_name}/{s3_config.app_name}/lastUpdate.json"

        self._cached_dict = None

    def get_active_store_codes(self) -> List[str]:
        if self._cached_dict is None:
            self._update_cache()

        return list(self._cached_dict.keys())

    def get_last_processed_day(self, store_code: str) -> Optional[date]:
        if self._cached_dict is None:
            self._update_cache()

        last_processed_str = self._cached_dict[store_code]
        if last_processed_str is None:
            return None

        return date.fromisoformat(last_processed_str)

    def set_last_processed_day(self, store_code: str, last_processed_day: date) -> None:
        if self._cached_dict is None:
            self._update_cache()

        self._cached_dict[store_code] = last_processed_day.isoformat()
        self.s3_client.put_object(
            Bucket=self.bucket_name,
            Key=self.control_file_path,
            Body=json.dumps(self._cached_dict).encode(),
        )

    def _update_cache(self):
        response = self.s3_client.get_object(
            Bucket=self.bucket_name,
            Key=self.control_file_path,
        )
        self._cached_dict = json.loads(response['Body'].read().decode())
