from datetime import (
    UTC,
    date,
    datetime,
)
from typing import Callable

from order_picture_base_model import OrderPicture


class OrderPictureFile(object):
    def __init__(
        self,
        full_path: str,
        record: dict,
    ):
        self.full_path = full_path
        self.business_date = OrderPictureFile.build_business_date(full_file_name=full_path)

        self.file_name = full_path.split("/")[-1]
        parts = self.file_name.split("-")

        self.store_code = parts[0]
        self.order_code = parts[1]

        created_at_str = parts[2]
        self.created_at = OrderPictureFile._parse_full_date(date_str=created_at_str)

        updated_at_str = parts[3]
        self.last_updated_at = OrderPictureFile._parse_full_date(date_str=updated_at_str)

        self.record = record
        self.order_picture = OrderPicture.create_from_dict(record=record)

    @staticmethod
    def build_business_date_filter(business_date: date) -> Callable[[str], bool]:
        def _filter(full_file_name: str) -> bool:
            return OrderPictureFile.build_business_date(full_file_name=full_file_name) == business_date

        return _filter

    @staticmethod
    def build_business_date(full_file_name: str) -> date:
        full_path_parts = full_file_name.split("/")
        if full_path_parts[2] == "processed":
            year_index = 5
        else:
            year_index = 3

        year = int(full_path_parts[year_index])
        month = int(full_path_parts[year_index + 1])
        day = int(full_path_parts[year_index + 2])
        return date(
            year=year,
            month=month,
            day=day,
        )

    @staticmethod
    def _parse_full_date(date_str: str) -> datetime:
        year = int(date_str[0:4])
        month = int(date_str[4:6])
        day = int(date_str[6:8])
        hour = int(date_str[8:10])
        minute = int(date_str[10:12])
        seconds = int(date_str[12:14])
        milliseconds = int(date_str[14:20])

        return datetime(
            year=year,
            month=month,
            day=day,
            hour=hour,
            minute=minute,
            second=seconds,
            microsecond=milliseconds,
            tzinfo=UTC,
        )

