import requests
import json
import logging
from airflow.settings import conf
from airflow.exceptions import AirflowConfigException

try:
    SLACK_URL = conf.get('slack', 'url')
    SLACK_ICON = conf.get('slack', 'icon') if conf.has_option('slack', 'icon') else ":zenyatta:"
    SLACK_USER = conf.get('slack', 'user')
    SLACK_CHANNEL = conf.get('slack', 'channel')
except AirflowConfigException as ae:
    SLACK_URL = SLACK_ICON = SLACK_USER = SLACK_CHANNEL = ""


def send_slack_message(text, url=SLACK_URL, channel=SLACK_CHANNEL, user=SLACK_USER, icon=SLACK_ICON):
    data = {
        "channel": channel,
        "username": user,
        "text": text,
        "icon_emoji": icon,
    }
    logging.info("posting to: {} data : {}".format(url, data))
    resp = requests.post(url, data=json.dumps(data))
    logging.info("result of slack post, content: {}".format(resp.content))
    return resp
