import json
from logging import Logger

from application.model import (
    PosVersions,
    UpdateType,
)
from application.repository.pos import VersionsPOSRepository
from typing import (
    Dict,
    Optional,
)


class GetVersionsInteractor(object):
    def __init__(
        self,
        pos_repository,             # type: VersionsPOSRepository
        path_to_catalog_json,       # type: str
        logger,                     # type: Logger
    ):
        # type: (...) -> None

        self.pos_repository = pos_repository
        self.path_to_catalog_json = path_to_catalog_json
        self.logger = logger

        self.menu_detail = None

    def get_versions(self):
        # type: () -> PosVersions

        last_versions, last_versions_dates = self.pos_repository.get_last_versions()
        if not self.menu_detail:
            self.menu_detail = self._get_menu_version_and_name(last_versions=last_versions)

        pos_versions = PosVersions(
            last_versions=last_versions,
            last_versions_dates=last_versions_dates,
            menu_version=self.menu_detail["version"],
            menu_name=self.menu_detail["name"],
        )

        return pos_versions

    def _get_menu_version_and_name(
        self,           # type: GetVersionsInteractor
        last_versions,  # type: Dict[int, str]
    ):
        # type: (...) -> Dict[Optional[str], Optional[str]]

        menu_detail = dict(
            version="",
            name="",
        )

        if not last_versions or not self.path_to_catalog_json:
            return menu_detail

        last_catalog_version = last_versions.get(UpdateType.catalog.value)
        try:
            with open(self.path_to_catalog_json, 'rb') as f:
                catalog_json = json.load(f)
                menu_version = last_catalog_version.split('_')[0]
                if catalog_json.get('version') == int(menu_version):
                    menu_id = int(last_catalog_version.split('_')[1])
                    for menu in catalog_json.get('menus', []):
                        if menu.get('id') == menu_id:
                            return dict(
                                version=menu_version,
                                name=(menu.get('name') or str(menu[id])).encode('utf-8'),
                            )
        except (Exception,):
            message = "Error getting menu version and name for version_catalog: {}"
            self.logger.exception(message.format(last_catalog_version))

        return menu_detail
