import logging

from poshelper import PosModelRetriever
from typing import (
    Dict,
)

logger = logging.getLogger(__name__)


class UsedServiceCache(object):
    def __init__(
        self,
        model_retriever,  # type: PosModelRetriever
    ):
        # type: (...) -> None

        self.model_retriever = model_retriever

        self.used_services = {}  # type: Dict[int, Dict[str, str]]

    def get_cached_object(
        self,           # type: UsedServiceCache
        device_type,    # type: str
        pos_id,         # type: str
    ):
        # type: (...) -> str

        if pos_id not in self.used_services:
            self.used_services[pos_id] = self._get_used_service(pos_id=pos_id)

        return self.used_services[pos_id].get(device_type)

    def _get_used_service(
        self,       # type: UsedServiceCache
        pos_id,     # type: int
    ):
        # type: (...) -> Dict[str, str]

        logger.info("Retrieving used services from POS{}".format(pos_id))
        ret = {}
        model = self.model_retriever.get_model(pos_id=pos_id)
        for service in model.findall("UsedServices/Service"):
            if service.get("default") == "true":
                ret[service.get("type")] = service.get("name")
        return ret
