from __future__ import unicode_literals, division, absolute_import
import logging

from flexget import plugin
from flexget.event import event
from flexget.utils import json
from flexget.utils.template import RenderError

log = logging.getLogger('slack')


class OutputSlack(object):
    """
    Example:

      slack:
        webhook-url: <string>
        [text: <string>] (default: "{{task}} - Download started: {{series_name}} {{series_id}}" -- accepts Jinja2)
        [channel: <string>] (override channel, use "@username" or "#channel")
        [username: <string>] (override username)
        [icon-emoji: <string>] (override emoji icon, do not include the colons: e.g., use "tv" instead of ":tv:")

    Configuration parameters are also supported from entries (e.g., through set).
    """
    default_body = ('{{task}} - Download started: '
                    '{% if series_name is defined %}'
                    '{{tvdb_series_name|d(series_name)}} {{series_id}} {{tvdb_ep_name|d('')}}'
                    '{% elif imdb_name is defined %}'
                    '{{imdb_name}} {{imdb_year}}'
                    '{% else %}'
                    '{{title}}'
                    '{% endif %}')
    schema = {
        'type': 'object',
        'properties': {
            'webhook-url': {'type': 'string'},
            'text': {'type': 'string', 'default': default_body},
            'channel': {'type': 'string'},
            'username': {'type': 'string'},
            'icon-emoji': {'type': 'string'},
        },
        'required': ['webhook-url'],
        'additionalProperties': False
    }

    @plugin.priority(0)
    def on_task_output(self, task, config):

        for entry in task.accepted:
            webhook_url = config.get('webhook-url')
            text = config.get('text')
            channel = config.get('channel')
            username = config.get('username')
            icon_emoji = config.get('icon-emoji')

            if icon_emoji:
                icon_emoji = ":%s:" % icon_emoji

            try:
                text = entry.render(text)
            except RenderError as e:
                log.warning('Problem rendering `text`: %s' % e)
                text = 'Download started'

            self.send_post(task, webhook_url, text, channel, username,
                           icon_emoji)

    def send_post(self, task, webhook_url, text, channel, username,
                  icon_emoji):

        data = {'text': text}
        if channel:
            data['channel'] = channel
        if username:
            data['username'] = username
        if icon_emoji:
            data['icon_emoji'] = icon_emoji

        if task.options.test:
            log.info('Test mode. Slack notification would be:')
            log.info('    Webhook URL: {}'.format(webhook_url))
            log.info('    Text: {}'.format(text))
            if channel:
                log.info('    Channel: {}'.format(channel))
            if username:
                log.info('    Username: {}'.format(username))
            if icon_emoji:
                log.info('    Icon Emoji: :{}:'.format(icon_emoji))
            log.info('    Raw POST Data: {}'.format(json.dumps(data)))
            # Early return (test mode)
            return

        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': 'Flexget'
        }
        try:
            response = task.requests.post(webhook_url, headers=headers,
                                          data=json.dumps(data),
                                          raise_status=False)
        except Exception as e:
            log.error('Unable to connect to Slack API: {}'.format(e))
            return

        response_code = response.status_code

        if response_code == 200:
            log.debug('Slack notification sent')
        elif response_code == 500:
            log.warning('Slack notification failed: server problem')
        elif response_code >= 400:
            log.error('Slack API error {}: {}'.format(response_code, response.content))
        else:
            log.error('Unknown error when sending Slack notification: {}'.format(response_code))


@event('plugin.register')
def register_plugin():
    plugin.register(OutputSlack, 'slack', api_ver=2)

@@ -2774,16 +2774,17 @@
 k URL: %7B
+0
 %7D'.forma
@@ -2832,16 +2832,17 @@
  Text: %7B
+0
 %7D'.forma
@@ -2914,16 +2914,17 @@
 annel: %7B
+0
 %7D'.forma
@@ -3001,16 +3001,17 @@
 rname: %7B
+0
 %7D'.forma
@@ -3094,16 +3094,17 @@
 moji: :%7B
+0
 %7D:'.form
@@ -3161,16 +3161,17 @@
  Data: %7B
+0
 %7D'.forma
@@ -3705,16 +3705,17 @@
 k API: %7B
+0
 %7D'.forma
@@ -4051,12 +4051,14 @@
 or %7B
+0
 %7D: %7B
+1
 %7D'.f
@@ -4182,16 +4182,17 @@
 ation: %7B
+0
 %7D'.forma

Use indicies when formatting strings