from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    LOCATION_CHOICES = [
        ('Canley', 'Canley'),
        ('Leamington Spa', 'Leamington Spa'),
        ('On-Campus', 'On-Campus'),
        ('Coventry', 'Coventry'),
        ('Other', 'Other'),
    ]
    LOOKING_FOR_CHOICES = [
        ('Friends', 'Friends'),
        ('Short-term', 'Short-term'),
        ('Long-term', 'Long-term'),
    ]
    YEAR_CHOICES = [
        ('Year 1', 'Year 1'),
        ('Year 2', 'Year 2'),
        ('Year 3', 'Year 3'),
        ('Year 4+', 'Year 4+'),
        ('Postgraduate', 'Postgraduate'),
    ]

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    course = models.CharField(max_length=255, blank=True)
    year = models.CharField(max_length=50, choices=YEAR_CHOICES, blank=True)
    location = models.CharField(max_length=50, choices=LOCATION_CHOICES, blank=True)
    looking_for = models.CharField(max_length=50, choices=LOOKING_FOR_CHOICES, blank=True)
    bio = models.TextField(max_length=500, blank=True)
    is_subscribed = models.BooleanField(default=False)
    last_online = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.user.username}'s profile"

    @property
    def primary_photo(self):
        primary = self.photos.filter(is_primary=True).first()
        if primary:
            return primary
        return self.photos.first()

class Photo(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='photos')
    image = models.ImageField(upload_to='profile_photos/')
    is_primary = models.BooleanField(default=False)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Photo for {self.profile.user.username}"

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()