# -*- encoding: utf-8 -*-

import logging
from uuid import uuid4
from pathlib import Path

from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.db.utils import IntegrityError
from django.db.models.signals import pre_save
from django.utils.translation import gettext_lazy as _
from django.core.files.storage import FileSystemStorage
from django.utils.deconstruct import deconstructible

log = logging.getLogger(__name__)


class OverwriteStorage(FileSystemStorage):
    """
    Storage class that allows overriding files, instead of django appending random
    characters to prevent conflicts.
    """

    def get_available_name(self, name, max_length=None) -> str:
        if self.exists(name):
            (Path(self.location) / name).unlink()

        return name


@deconstructible
class IconPathGenerator:
    """
    Icon path generator.
    """

    def __call__(self, instance, filename: str) -> Path:
        return Path(instance.__class__.__name__.lower()) / str(instance.uuid) / "icon.webp"


class SavedGuilds(models.Model):
    """
    
    """

    id = models.AutoField(
        primary_key=True
    )

    # Have to use charfield instead of positiveBigIntegerField due to an Sqlite
    # issue that rounds down the value
    # https://github.com/sequelize/sequelize/issues/9335
    guild_id = models.CharField(
        max_length=128,
    )

    name = models.CharField(
        max_length=128
    )

    icon = models.CharField(
        max_length=128
    )

    added_by = models.ForeignKey(to="authentication.DiscordUser", on_delete=models.CASCADE)

    permissions = models.CharField(
        max_length=64
    )

    owner = models.BooleanField(
        default=False
    )


class Subscription(models.Model):
    id = models.AutoField(
        primary_key=True
    )

    name = models.CharField(
        max_length=32,
        null=False,
        blank=False
    )

    url = models.URLField()

    # Have to use charfield instead of positiveBigIntegerField due to an Sqlite
    # issue that rounds down the value
    # https://github.com/sequelize/sequelize/issues/9335
    guild_id = models.CharField(
        max_length=128
    )

    creation_datetime = models.DateTimeField(
        default=timezone.now,
        editable=False
    )

    extra_notes = models.CharField(
        max_length=250,
        null=True,
        blank=True,
    )

    active = models.BooleanField(
        default=True,
    )

    class Meta:
        """
        Metadata for the Subscription Model.
        """

        verbose_name = "subscription"
        verbose_name_plural = "subscriptions"
        get_latest_by = "-creation_datetime"
        constraints = [
            # Prevent servers from having subscriptions with duplicate names
            models.UniqueConstraint(fields=["name", "guild_id"], name="unique name & server pair")
        ]

    @property
    def channels_count(self):
        return 0

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        new_text = "New " if self._state.adding else ""
        log.debug("%sSubscription Saved %s", new_text, self.id)
        super().save(*args, **kwargs)

