from dataclasses import dataclass

from django.db import models
from django.urls import reverse
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFit
from scrobbles.mixins import LongPlayScrobblableMixin

from vrobbler.apps.scrobbles.dataclasses import (
    BaseLogData,
    LongPlayLogData,
    WithPeopleLogData,
)

BNULL = {"blank": True, "null": True}


@dataclass
class BrickSetLogData(BaseLogData, WithPeopleLogData, LongPlayLogData):
    pass


class BrickSet(LongPlayScrobblableMixin):
    """"""

    number = models.CharField(max_length=10, **BNULL)
    release_year = models.IntegerField(**BNULL)
    piece_count = models.IntegerField(**BNULL)
    brickset_rating = models.DecimalField(max_digits=3, decimal_places=1, **BNULL)
    lego_item_number = models.CharField(max_length=10, **BNULL)
    box_image = models.ImageField(upload_to="brickset/boxes/", **BNULL)
    box_image_small = ImageSpecField(
        source="box_image",
        processors=[ResizeToFit(100, 100)],
        format="JPEG",
        options={"quality": 60},
    )
    box_image_medium = ImageSpecField(
        source="box_image",
        processors=[ResizeToFit(300, 300)],
        format="JPEG",
        options={"quality": 75},
    )
    set_image = models.ImageField(upload_to="brickset/sets/", **BNULL)
    set_image_small = ImageSpecField(
        source="set_image",
        processors=[ResizeToFit(100, 100)],
        format="JPEG",
        options={"quality": 60},
    )
    set_image_medium = ImageSpecField(
        source="set_image",
        processors=[ResizeToFit(300, 300)],
        format="JPEG",
        options={"quality": 75},
    )

    def get_absolute_url(self):
        return reverse("bricksets:brickset_detail", kwargs={"slug": self.uuid})

    def __str__(self) -> str:
        name = str(self.title)
        if not self.title:
            name = str(self.number)
        return name

    @property
    def logdata_cls(self):
        return BrickSetLogData

    @classmethod
    def find_or_create(cls, brickset_id: str) -> "BrickSet":
        brickset = cls.objects.filter(number=brickset_id).first()
        if not brickset:
            # TODO: enrich this from the website
            brickset = cls.objects.create(number=brickset_id)
        return brickset

    @property
    def primary_image_url(self) -> str:
        if self.box_image:
            return self.box_image.url
        return ""
