import time

import requests
from application.configurator import Configurator
from application.model import EventData
from syserrors import SE_BADRESPONSE, SE_SUCCESS, SE_CONNECT
from typing import Optional


class EventSender(object):

    def __init__(self, configurations):
        # type: (Configurator) -> None

        self.configs = configurations
        self.logger = self.configs.logger

    def send_request(self, event_data, payload, include_store_id=False):
        # type: (EventData, str, Optional[bool]) -> int

        try:
            payload = payload.encode("utf-8")
            self.logger.info("[{}] Sending event to server. Payload:\n{}".format(event_data.type, payload))

            headers = {
                    "Accept": "application/json",
                    "Content-type": "application/json",
                    "x-api-key": self.configs.api_key
            }

            post_url = self.configs.server_url + self.configs.views.get(event_data.type)
            if include_store_id:
                post_url += "/{}".format(self.configs.store_id)

            response = requests.post(post_url, headers=headers, data=payload, timeout=30, verify=False)  # NOSONAR

            if response.status_code != 200:
                log_message = "[{0}] Error sending event to server. Status: {1} - {2}"
                self.logger.info(log_message.format(event_data.type, response.status_code, response.content))
                time.sleep(self.configs.retry_wait / 1000.0)
                return SE_BADRESPONSE

            self.logger.info("[{}] Success sending event to server".format(event_data.type))
            return SE_SUCCESS

        except Exception as _:
            message = "[{}] Communication error sending event to server".format(event_data.type)
            self.logger.exception(message)
            return SE_CONNECT
