from xml.etree import cElementTree as eTree

from sysactions import get_model

from devicemanager.model import GetUsedServiceRequest
from devicemanager.util import CacheManager
from typing import Optional


class GetUsedServiceInteractor(object):
    def __init__(
        self,
        cache_manager,  # type: CacheManager
    ):
        # type: (...) -> None

        self.cache_manager = cache_manager

    def process_request(
        self,
        get_used_service_request,   # type: GetUsedServiceRequest
    ):
        # type: (...) -> str

        model = get_model(get_used_service_request.pos_id)
        device = self.cache_manager.get_cached_object(
            sector=get_used_service_request.sector,
            device_type=get_used_service_request.device_type,
            pos_id=get_used_service_request.pos_id,
            method_to_obtain_cache=self.get_used_service,
            method_to_obtain_cache_params=(
                model,
                get_used_service_request.device_type
            ),
        )
        return device

    @staticmethod
    def get_used_service(
        model,          # type: eTree.XML
        service_type,   # type: str
    ):
        # type: (...) -> Optional[str]

        services = [node for node in model.findall("UsedServices/Service") if node.get("type") == service_type]
        for service in services:
            if service.get("default") == "true":
                return str(service.get("name"))
        return None
