from abc import ABC, abstractmethod
import requests

from django.conf import settings
from django.contrib.sites.models import Site

class Notification(ABC):
    scrobble: "Scrobble"
    ntfy_headers: dict = {}
    ntfy_url: str = ""
    title: str = ""

    def __init__(self, scrobble: "Scrobble"):
        self.scrobble = scrobble
        self.user = scrobble.user
        self.media_obj = scrobble.media_obj
        protocol = "http" if settings.DEBUG else "https"
        domain = Site.objects.get_current().domain
        self.url_tmpl = f'{protocol}://{domain}' + '{path}'



    @abstractmethod
    def send(self) -> None:
        pass


class NtfyNotification(Notification):
    def __init__(self, scrobble, **kwargs):
        super().__init__(scrobble)
        self.ntfy_str: str = f"{self.scrobble.media_obj}"
        self.click_url = self.url_tmpl.format(path=self.media_obj.get_absolute_url())
        self.title = self.media_obj.strings.verb
        if kwargs.get("end", False):
            self.click_url = self.url_tmpl.format(path=self.scrobble.finish_url)
            self.title = "Finish " + self.media_obj.strings.verb.lower() + "?"

        if self.scrobble.log and isinstance(self.scrobble.log, dict) and self.scrobble.log.get("description"):
            self.ntfy_str += f" - {self.scrobble.log.get('description')}"

    def send(self):
        if (
            self.user
            and self.user.profile
            and self.user.profile.ntfy_enabled
            and self.user.profile.ntfy_url
        ):
            requests.post(
                self.user.profile.ntfy_url,
                data=self.ntfy_str.encode(encoding="utf-8"),
                headers={
                    "Title": self.title,
                    "Priority": self.media_obj.strings.priority,
                    "Tags": self.media_obj.strings.tags,
                    "Click": self.click_url,
                },
            )
