# coding: utf-8

import json

import requests
from sentry.plugins.bases.notify import NotificationPlugin

import sentry_dingtalk_robot
from .forms import DingDingOptionsForm

DingTalk_API = "https://oapi.dingtalk.com/robot/send?access_token={token}"


class DingDingPlugin(NotificationPlugin):
    """
    Sentry plugin to send error counts to DingDing.
    """
    author = 'loopbless'
    author_url = 'https://github.com/loopbless/sentry-dingding'
    version = sentry_dingtalk_robot.VERSION
    description = 'Send error counts to DingDing.'
    resource_links = [
        ('Source', 'https://github.com/loopbless/sentry-dingding'),
        ('Bug Tracker', 'https://github.com/loopbless/sentry-dingding/issues'),
        ('README', 'https://github.com/loopbless/sentry-dingding/blob/master/README.md'),
    ]

    slug = 'DingTalkRobot'
    title = 'DingTalkRobot'
    conf_key = slug
    conf_title = title
    project_conf_form = DingDingOptionsForm

    def is_configured(self, project):
        """
        Check if plugin is configured.
        """
        return bool(self.get_option('access_token', project))

    def notify_users(self, group, event, *args, **kwargs):
        self.post_process(group, event, *args, **kwargs)

    def post_process(self, group, event, *args, **kwargs):
        """
        Process error.
        """
        if not self.is_configured(group.project):
            return

        if group.is_ignored():
            return

        access_token = self.get_option('access_token', group.project)
        project_title = self.get_option('title', group.project) or u"New alert from {name}"
        content = self.get_option('content', group.project) or u"#### {title} \n > {message} [href]({url})"
        send_url = DingTalk_API.format(token=access_token)
        title = project_title.format(name=event.project.slug)
        data = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": content.format(
                    title=title,
                    message=event.message,
                    url=u"{}events/{}/".format(group.get_absolute_url(), event.event_id),
                )
            }
        }
        requests.post(
            url=send_url,
            headers={"Content-Type": "application/json"},
            data=json.dumps(data).encode("utf-8")
        )
