#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

import requests

import equipment_watcher.settings as settings
from .base import Notifier


class SlackNotifier(Notifier):

    def __init__(self, token=None, channel=None):
        channel = channel or settings.SLACK_CHANNEL
        super(SlackNotifier, self).__init__(channel=channel)
        self.token = token or settings.SLACK_TOKEN

    def get_usernames(self, user_ids=()):
        usernames = []
        for user_id in user_ids:
            user_response = requests.post(
                'https://slack.com/api/users.info',
                data={'token': self.token, 'user': user_id}
            ).json()
            if user_response['ok']:
                user = user_response.get('user')
                if user:
                    usernames.append(user['name'])
        return usernames

    def set_topic(self, topic, **kwargs):
        payload = {
            'topic': topic,
            'token': self.token,
            'channel': self.channel,
        }
        requests.post('https://slack.com/api/channels.setTopic', data=payload)

    def send_message(self, message, username='poseidon', emoji=None, highlight=False):
        payload = {
            'token': self.token,
            'channel': self.channel,
            'username': username,
        }
        if emoji is not None:
            payload['icon_emoji'] = emoji
        if highlight:
            # Using @channel does not notify the channel
            # Notify each user separately
            response_json = requests.post(
                'https://slack.com/api/channels.info',
                data={'token': self.token, 'channel': self.channel},
            ).json()
            if response_json['ok']:
                usernames = self.get_usernames(response_json['channel']['members'])
                message = u"{} ({})".format(message, ', '.join(usernames))
            else:
                sys.stderr.write(u"ERROR: Couldn't retrieve channel user list, not notifying\n")
                sys.stderr.write(u"ERROR: {}".format(response_json))

        payload['text'] = message
        requests.post('https://slack.com/api/chat.postMessage', data=payload)
