

# Create your models here.
from django.db import models
from urllib.parse import urlparse
from django.utils.translation import get_language

class Carousel(models.Model):
    # Slide 1
    subtitle_1 = models.CharField(max_length=255, blank=True, null=True)
    content_1 = models.TextField(blank=True, null=True)
    image_1 = models.ImageField(upload_to='carousel/')
    mobile_image_1 = models.ImageField(upload_to='carousel/', blank=True, null=True)
    button_text_1 = models.CharField(max_length=100, blank=True, null=True)
    button_link_1 = models.URLField(blank=True, null=True)

    # Slide 2
    subtitle_2 = models.CharField(max_length=255, blank=True, null=True)
    content_2 = models.TextField(blank=True, null=True)
    image_2 = models.ImageField(upload_to='carousel/')
    mobile_image_2 = models.ImageField(upload_to='carousel/', blank=True, null=True)
    button_text_2 = models.CharField(max_length=100, blank=True, null=True)
    button_link_2 = models.URLField(blank=True, null=True)

    # Slide 3
    subtitle_3 = models.CharField(max_length=255, blank=True, null=True)
    content_3 = models.TextField(blank=True, null=True)
    image_3 = models.ImageField(upload_to='carousel/')
    mobile_image_3 = models.ImageField(upload_to='carousel/', blank=True, null=True)
    button_text_3 = models.CharField(max_length=100, blank=True, null=True)
    button_link_3 = models.URLField(blank=True, null=True)

    def __str__(self):
        return "Homepage Carousel"

    def save(self, *args, **kwargs):
        if not self.pk and Carousel.objects.exists():
            raise ValueError("Only one Carousel instance is allowed.")
        super().save(*args, **kwargs)

    def _localize(self, link):
        if not link:
            return ""
        parsed = urlparse(link)
        base = f"{parsed.scheme}://{parsed.netloc}"
        if get_language() == "en":
            return f"{base}/en{parsed.path}"
        return f"{base}{parsed.path}"

    @property
    def localized_button_link_1(self):
        return self._localize(self.button_link_1)

    @property
    def localized_button_link_2(self):
        return self._localize(self.button_link_2)

    @property
    def localized_button_link_3(self):
        return self._localize(self.button_link_3)

    class Meta:
        verbose_name = "Carousel Section"
        verbose_name_plural = "Carousel Section"
