#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
(Data)models which describe the structure of data to be saved into 
database.
'''

import os
import uuid

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _

from lostplaces.models.abstract_models import Expireable
from lostplaces.models.place import Place

from easy_thumbnails.fields import ThumbnailerImageField
from easy_thumbnails.files import get_thumbnailer

def generate_profile_image_filename(instance, filename):
    """
    Callback for generating filename for uploaded explorer profile images.
    Returns filename as: explorer_pk-username.jpg
    """

    return 'explorers/' + str(instance.user.pk) + '-' + str(instance.user.username) + '.' + filename.split('.')[-1]

EXPLORER_LEVELS = (
    (1, 'Newbie'),
    (2, 'Scout'),
    (3, 'Explorer'),
    (4, 'Journalist'),
    (5, 'Housekeeper')
)

class Explorer(models.Model):
    """
    Profile that is linked to the Django user.
    Every user has a profile.
    Provides additional attributes for user profile.
    """
    
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='explorer'
    )
    bio = models.TextField(
        blank=True,
        null=True,
        verbose_name=_('Biography / Description'),
        help_text=_('Describe yourself, your preferences, etc. in a few sentences.')
    )
    profile_image = ThumbnailerImageField(
        blank=True,
        null=True,
        upload_to=generate_profile_image_filename, 
        resize_source=dict(size=(400, 400), 
        sharpen=True),
        verbose_name=_('Profile image'),
        help_text=_('Optional profile image for display in Explorer profile')
    )
    favorite_places = models.ManyToManyField(
        Place,
        related_name='explorer_favorites',
        verbose_name='Explorers favorite places',
        blank=True
    )
    visited_places = models.ManyToManyField(
        Place,
        related_name='explorer_visits',
        verbose_name='Explorers visited places',
        blank=True
    )

    level = models.IntegerField(
        default=1,
        choices=EXPLORER_LEVELS
    )

    def get_places_eligible_to_see(self):
        if self.user.is_superuser:
            return Place.objects.all()
        return Place.objects.all().filter(level__lte=self.level) | self.places.all()

    def is_eligible_to_see(self, place):
        return (
            self.user.is_superuser or
            place.submitted_by == self or
            place in self.get_places_eligible_to_see()
        )

    def __str__(self):
        return self.user.username

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

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

@receiver(pre_save, sender=Explorer)
def auto_delete_file_on_change(sender, instance, **kwargs):
    """
    Deletes old file from filesystem
    when corresponding `Explorer` object is updated
    with new file.
    """
    if not instance.pk:
        return False

    try:
        old_file = Explorer.objects.get(pk=instance.pk).profile_image
    except Explorer.DoesNotExist:
        return False
    new_file = instance.profile_image
    if not old_file == new_file:
        old_file.delete(save=False)

class Voucher(Expireable):
    """
    Vouchers are authorization tokens to allow the registration of new users.
    A voucher has a code, a creation and a deletion date, which are all 
    positional. Creation date is being set automatically during voucher 
    creation. 

    created_when = models.DateTimeField(auto_now_add=True)
    expires_when = models.DateTimeField()
    """

    code = models.CharField(unique=True, max_length=30)
    
    @property
    def valid(self):
        return not self.is_expired

    def __str__(self):
        return "Voucher " + str(self.code)
