from logging import Logger

from model.config import Config
from model.electronic_message import ElectronicMessage
from model.error_type import PosValidationErrorsType
from model.exception import ValidationError
from model.repository import PosRepositoryModel
from model.services import FiscalServiceModel
from interactor.route.electronic_payment.read_messages.dto import (
    ReadMessagesRequest,
    ReadMessagesResponse
)
from validation_util import validate_api_key, check_if_business_day_is_opened, \
    check_if_operator_is_logged, check_if_order_is_totaled
from typing import List


class ReadMessagesInteractor(object):
    def __init__(self, logger, config, pos_repository, fiscal_service, electronic_messages):
        # type: (Logger, Config, PosRepositoryModel, FiscalServiceModel, List[ElectronicMessage]) -> None

        self.logger = logger
        self.config = config
        self.pos_repository = pos_repository
        self.fiscal_service = fiscal_service
        self.electronic_messages = electronic_messages

    def execute(self, request):
        # type: (ReadMessagesRequest) -> ReadMessagesResponse

        pos_id = validate_api_key(request, self.config.api_key_mapping)
        if not pos_id:
            raise ValidationError(PosValidationErrorsType.PosIdNotFound)

        model = self.pos_repository.get_model(pos_id)

        check_if_business_day_is_opened(self.pos_repository, model)
        check_if_operator_is_logged(self.pos_repository, model)
        check_if_order_is_totaled(self.pos_repository, model)

        pos_id = int(pos_id)
        self._remove_read_messages(pos_id, request)

        response_electronic_messages = self._get_response_messages(pos_id, request)

        return response_electronic_messages

    def _remove_read_messages(self, pos_id, request):
        # type: (int, ReadMessagesRequest) -> None

        for message_id in request.read_messages_id:
            for electronic_message in self.electronic_messages[:]:
                if electronic_message.message_id == message_id and electronic_message.pos_id == pos_id:
                    self.electronic_messages.remove(electronic_message)

    def _get_response_messages(self, pos_id, request):
        # type: (int, ReadMessagesRequest) -> List[ElectronicMessage]

        response_messages = []
        for electronic_message in self.electronic_messages:
            if int(electronic_message.pos_id) == int(pos_id):
                electronic_message.pos_id = int(request.pos_id)
                response_messages.append(electronic_message)
        return response_messages
