from logging import Logger

import requests
from helper import json_serialize, retry
from model.config import Config
from model.electronic_message import ElectronicMessage
from model.error_type import ExternalServicesErrorsType
from model.exception import ExternalServiceErrors
from model.services import ApiServiceModel


class ApiService(ApiServiceModel):

    def __init__(self, config, logger):
        # type: (Config, Logger) -> None

        self.config = config
        self.logger = logger

    def send_electronic_messages(self, electronic_messages):
        # type: (ElectronicMessage) -> None

        url = "http://{}:{}/cache/peripheral/electronicPayment".format(self.config.host, self.config.port)
        headers = {"Content-type": "application/json"}
        data = json_serialize({"electronicMessage": electronic_messages})

        response = retry(
                logger=self.logger,
                method_name="send_electronic_messages",
                n=3,
                sleep_seconds=5,
                trying_to_do=lambda: requests.request("POST", url=url, headers=headers, timeout=5, data=data),
                is_success=lambda resp: resp.status_code == 204,
                success=lambda resp: resp,
                failed=lambda resp: resp)

        if not response:
            raise ExternalServiceErrors(ExternalServicesErrorsType.ElectronicMessageUnavailable)
