# Path: cardinal/decorators.py
# def event(triggers):
#     if isinstance(triggers, str):
#         triggers = [triggers]
# 
#     if not isinstance(triggers, list):
#         raise TypeError("Event must be a trigger string or list of triggers")
# 
#     def wrap(f):
#         f.events = triggers
#         return f
# 
#     return wrap
# 
# Path: cardinal/exceptions.py
# class EventRejectedMessage(CardinalException):
#     """Raised when an event callback wants to reject an event."""


import logging
import re
import requests
from urllib.parse import urlparse
from twisted.internet import defer
from twisted.internet.threads import deferToThread
from cardinal.decorators import event
from cardinal.exceptions import EventRejectedMessage




class ImgurPlugin:
    def __init__(self, config):
        self.logger = logging.getLogger(__name__)
        self.api = ImgurApi(config['client_id'])

    @event("urls.detection")
    @defer.inlineCallbacks
    def handle_url(self, cardinal, channel, url):
        o = urlparse(url)
        if o.netloc not in ('i.imgur.com', 'imgur.com'):
            raise EventRejectedMessage

        # it's not really possible to tell if this is an image or an album
        if match := re.match(r'^(?:.*?)/(\w+)(?:\.\w+)?$', o.path):
            imgur_hash = match.group(1)
            try:
                image = yield self.api.get_image(imgur_hash)
                cardinal.sendMsg(channel, self.format_image(image))
                return
            except requests.exceptions.HTTPError:
                # probably not an image. no support for other types currently
                raise EventRejectedMessage


# Path: cardinal/decorators.py
# def event(triggers):
#     if isinstance(triggers, str):
#         triggers = [triggers]
# 
#     if not isinstance(triggers, list):
#         raise TypeError("Event must be a trigger string or list of triggers")
# 
#     def wrap(f):
#         f.events = triggers
#         return f
# 
#     return wrap
# 
# Path: cardinal/exceptions.py
# class EventRejectedMessage(CardinalException):
#     """Raised when an event callback wants to reject an event."""


# Path: plugins/imgur/plugin.py
import logging
import re
import requests
from urllib.parse import urlparse
from twisted.internet import defer
from twisted.internet.threads import deferToThread
from cardinal.decorators import event
from cardinal.exceptions import EventRejectedMessage





class ImgurPlugin:
    def __init__(self, config):
        self.logger = logging.getLogger(__name__)
        self.api = ImgurApi(config['client_id'])

    @event("urls.detection")
    @defer.inlineCallbacks
    def handle_url(self, cardinal, channel, url):
        o = urlparse(url)
        if o.netloc not in ('i.imgur.com', 'imgur.com'):
            raise EventRejectedMessage

        # it's not really possible to tell if this is an image or an album
        if match := re.match(r'^(?:.*?)/(\w+)(?:\.\w+)?$', o.path):
            imgur_hash = match.group(1)
            try:
                image = yield self.api.get_image(imgur_hash)
                cardinal.sendMsg(channel, self.format_image(image))
                return
            except requests.exceptions.HTTPError:
                # probably not an image. no support for other types currently
                raise EventRejectedMessage


        raise EventRejectedMessage