from exceptions import MissingBearerTokenException
from messaging.email.mailbag import MailBag
from transport.request_executor import RequestExecutor


class EmailApiTransport:

    def __init__(self, bearer_token, proxies=None, logger=None):
        """
        :param bearer_token: Bearer Token generated by FreshMail
        :type bearer_token: str
        :param proxies: Proxies to use
        :type proxies: dict
        :param logger: Logger object to use
        :type logger: logging.Logger
        """
        self.__request_executor = RequestExecutor(logger=logger)
        self.bearer_token = bearer_token
        self.proxies = proxies
        self.logger = None

    def send(self, message):
        """
        :param message: The main message object which contains all data required to sending
        :return: Response from request executor
        """
        response = self.__request_executor.post('messaging/emails', message, self.__bearer_token, proxies=self.proxies)
        return response

    def is_supported(self, message):
        """
        Returns boolean value if given message type is handled by this Transport

        :param message: The main message object which contains all data required to sending
        :return: bool
        """
        return isinstance(message, MailBag)

    @property
    def bearer_token(self):
        """
        :return: Bearer Token generated by FreshMail
        """
        return self.__bearer_token

    @bearer_token.setter
    def bearer_token(self, token):
        if type(token) == str:
            self.__bearer_token = token
        else:
            raise MissingBearerTokenException

    def set_logger(self, logger):
        """
        :param logger: Logger object to use
        :type logger: logging.Logger
        """
        self.logger = logger
        self.__request_executor.set_logger(logger)
