import logging
from datetime import datetime

from typing import List

from actions import mb_context
from application.repository import UserRepository
from utilfunctions import get_seconds_to_renew_cache, reached_seconds_to_renew_cache

own_delivery_men = []
last_cache_time = None


class UserInteractor(object):
    def __init__(
            self
    ):
        # type: (...) -> None

        self.logger = logging.getLogger("PosActions")
        self.user_repository = UserRepository(mb_context)

    def get_own_delivery_men(
            self
    ):
        # type: (...) -> List

        global own_delivery_men
        global last_cache_time

        try:
            seconds_to_renew = get_seconds_to_renew_cache(60 * 5)
            if not own_delivery_men or reached_seconds_to_renew_cache(last_cache_time, seconds_to_renew):
                own_delivery_men = self.user_repository.get_own_delivery_men()
                last_cache_time = datetime.now()

            return [delivery_men.get("name", "") for delivery_men in own_delivery_men]
        except Exception as _:
            self.logger.exception("Error getting own delivers")
            return []
