'''
Documentation for Slack Incoming Webhook:
    https://api.slack.com/messaging/webhooks
'''
from logging import getLogger
import requests

logger = getLogger(__name__)


class SlackWebhookException(Exception):
    def __init__(self, message):
        self.message = message

    def __str__(self):
        return self.message


class SlackWebhook():
    """Class for sending notification to Slack via Incoming Webhook

    Parameters
    ----------
    url : str
        URL generated by the Slack administor for the incoming-webhook app
    channel : str
        channel name (not supported by all URL/App, depending on how it's setup)
    username : str
        overwrite username on the message (not supported by all URL/App, depending
        on administrator setting)
    icon_emoji : str
        name of emoji as the avatar of the user. (not supported by all URL/App)
    """
    def __init__(self, url, channel=None, username=None,
                 icon_emoji=None):
        self._channel = channel
        self._url = url
        self._username = username
        self._icon_emoji = icon_emoji

    def send(self, text="", blocks=None):
        """send a text message into the configured channel

        Parameters
        ----------
        text : str
            Text to be sent
        """
        payload = {
            'text': text
        }
        if blocks:
            payload['blocks'] = blocks
        if self.channel:
            payload['channel'] = self.channel
        if self.username:
            payload['username'] = self.username
        if self.icon_emoji:
            payload['icon_emoji'] = self.icon_emoji

        try:
            r = requests.post(self.url, json=payload)
            if r.status_code == 404:
                raise SlackWebhookException('API call return 404 error')
            elif r.status_code != 200:
                raise SlackWebhookException(f'Abnormal status sode from API call:'
                                            f' {r.status_code} ({r.text})')
        except SlackWebhookException as e:
            logger.error(e)

        return r

    @property
    def channel(self):
        return self._channel

    @property
    def url(self):
        return self._url

    @property
    def username(self):
        return self._username

    @property
    def icon_emoji(self):
        return self._icon_emoji
