import uuid
from django.db import models
from django.conf import settings
from vontor_cz.custom_fields import WebPImageField
from vontor_cz.models import SoftDeleteModel

from django.core.exceptions import ValidationError

# Create your models here.


class Hub(SoftDeleteModel):
    AUTHOR_FIELD = 'owner'

    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(blank=True, null=True)

    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        related_name='owned_hubs'
    )

    icon = WebPImageField(upload_to='hub_icons/', null=True, blank=True)
    banner = WebPImageField(upload_to='hub_banners/', null=True, blank=True)

    members = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='hubs',
        blank=True
    )

    is_public = models.BooleanField(default=True)



    transfer_to = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='pending_hub_transfers'
    )
    transfer_token = models.UUIDField(null=True, blank=True, unique=True)

    def create_transfer(self, new_owner):
        self.transfer_to = new_owner
        self.transfer_token = uuid.uuid4()
        self.save(update_fields=['transfer_to', 'transfer_token'])

    def verify_transfer(self, input_token, triggering_user):
        """Requires uuid and triggering user must match the transfer_to field"""
        if self.transfer_token and str(self.transfer_token) == str(input_token) and self.transfer_to == triggering_user:
            self.owner = self.transfer_to
            
            self.transfer_to = None
            self.transfer_token = None

            self.save(update_fields=['owner', 'transfer_to', 'transfer_token'])
            return True
        raise ValidationError("Invalid transfer token or user does not match transfer_to field")

    def cancel_transfer(self):
        self.transfer_to = None
        self.transfer_token = None
        self.save(update_fields=['transfer_to', 'transfer_token'])

    def get_all_tags(self):
        return Tags.objects.filter(hub_id=self.id)

    def __str__(self):
        return self.name
    
class HubPermission(SoftDeleteModel):
    hub = models.ForeignKey(Hub, on_delete=models.CASCADE, related_name='moderators')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    changing_name = models.BooleanField(default=False)
    changing_description = models.BooleanField(default=False)
    changing_icon = models.BooleanField(default=False)
    changing_banner = models.BooleanField(default=False)

    managing_members = models.BooleanField(default=False)
    managing_posts = models.BooleanField(default=False)
    managing_chats = models.BooleanField(default=False)

    class Meta:
        unique_together = ('hub', 'user')

    def __str__(self):
        return f"{self.user} moderates {self.hub}"
    
    
class Tags(SoftDeleteModel):
    hub = models.ForeignKey(Hub, on_delete=models.CASCADE, related_name='tags')
    name = models.CharField(max_length=50)

    description = models.TextField(blank=True, null=True)

    color = models.CharField(max_length=7, default='#000000')  # Hex color code