# -*- coding: utf-8 -*-

from django.contrib.auth.models import User
from django.db import models
from hdabo.fields import SortedManyToManyField
from hdabo.utils import Property
import datetime

class Organisation(models.Model):
    hda_id = models.CharField(max_length=512, unique=True, blank=False, null=False)
    name = models.CharField(max_length=512, unique=False, blank=False, null=False)
    location = models.CharField(max_length=512, unique=False, blank=True, null=True)
    website = models.CharField(max_length=2048, unique=False, blank=True, null=True)
    

class Author(models.Model):
    hda_id = models.CharField(max_length=512, unique=True, blank=False, null=False)
    lastname = models.CharField(max_length=512, unique=False, blank=True, null=True)
    firstname = models.CharField(max_length=512, unique=False, blank=True, null=True)

class TimePeriod(models.Model):
    TIME_PERIOD_CHOICES = (
        (1, u'Primaire'),
        (2, u'Collège'),
        (3, u'Lycée'),
    )
    TIME_PERIOD_DICT = {
        u'Primaire': 1,
        u'Collège': 2,
        u'Lycée': 3,
    }
    label = models.CharField(max_length=512, unique=False, blank=False, null=False)
    school_period = models.IntegerField(choices=TIME_PERIOD_CHOICES)
    
    class Meta:
        unique_together = ("label", "school_period")

    def __unicode__(self):
        return unicode(self.label)


class Domain(models.Model):
    DOMAIN_PERIOD_CHOICES = (
        (0, u'Global'),
        (1, u'Primaire'),
        (2, u'Collège'),
        (3, u'Lycée'),
    )
    DOMAIN_PERIOD_DICT = {
        u'Global': 0,
        u'Primaire': 1,
        u'Collège': 2,
        u'Lycée': 3,
    }
    label = models.CharField(max_length=512, unique=False, blank=False, null=False)
    school_period = models.IntegerField(choices=DOMAIN_PERIOD_CHOICES)

    class Meta:
        unique_together = ("label", "school_period")

    def __unicode__(self):
        return unicode(self.label)


class DocumentFormat(models.Model):
    label = models.CharField(max_length=512, unique=True, blank=False, null=False)

    def __unicode__(self):
        return unicode(self.label)
    
class TagCategory(models.Model):
    label = models.CharField(max_length=512, unique=True, blank=False, null=False)
    
    def __unicode__(self):
        return unicode(self.label)
    
    class Meta:
        verbose_name_plural = "TagCategories"

class Tag(models.Model):
    TAG_URL_STATUS_CHOICES = (
        (0, "null_result"),
        (1, "redirection"),
        (2, "homonyme"),
        (3, "match"),
    )
    
    TAG_URL_STATUS_DICT = {
        "null_result":0,
        "redirection":1,
        "homonyme":2,
        "match":3,
    }
    
    label = models.CharField(max_length=1024, unique=False, blank=False, null=False, db_index=True)
    original_label = models.CharField(max_length=1024, unique=True, blank=False, null=False, editable=False)
    alias = models.CharField(max_length=1024, unique=False, blank=True, null=True)
    category = models.ForeignKey(TagCategory, null=True, blank=True)
    wikipedia_url = models.URLField(verify_exists=False, max_length=2048, blank=True, null=True)
    wikipedia_pageid = models.BigIntegerField(unique=False, blank=True, null=True)
    url_status = models.IntegerField(choices=TAG_URL_STATUS_CHOICES, blank=True, null=True, default=None)
    dbpedia_uri = models.URLField(verify_exists=False, max_length=2048, blank=True, null=True)
    popularity = models.IntegerField(blank=False, null=False, default=0, db_index=True)

    @Property
    def url_status_text(): #@NoSelf
        def fget(self):
            return self.TAG_URL_STATUS_CHOICES[self.url_status][1]
        
        return locals() 
        
class Location(models.Model):
    name = models.CharField(max_length=512, unique=False, blank=False, null=False)
    insee = models.CharField(max_length=5, unique=True, blank=False, null=False)

    def __unicode__(self):
        return unicode("%s : %s" % (self.name, self.insee))

class Datasheet(models.Model):
    hda_id = models.CharField(max_length=512, unique=True, blank=False, null=False)
    author = models.ForeignKey(Author, null=True, blank=True)
    organisation = models.ForeignKey(Organisation)
    title = models.CharField(max_length=2048, unique=False, blank=False, null=False)
    description = models.TextField(blank=True, null=True)
    url = models.URLField(verify_exists=False, max_length=2048, blank=True, null=True)
    domains = SortedManyToManyField(Domain, limit_choices_to={'school_period':Domain.DOMAIN_PERIOD_DICT[u'Global']}, related_name="datasheets")
    primary_periods = SortedManyToManyField(TimePeriod, limit_choices_to={'school_period':TimePeriod.TIME_PERIOD_DICT[u'Primaire']}, related_name="primary_periods_datasheets")
    college_periods = SortedManyToManyField(TimePeriod, limit_choices_to={'school_period':TimePeriod.TIME_PERIOD_DICT[u'Collège']}, related_name="college_periods_datasheets")
    highschool_periods = SortedManyToManyField(TimePeriod, limit_choices_to={'school_period':TimePeriod.TIME_PERIOD_DICT[u'Lycée']}, related_name="highschool_periods_datasheets")
    primary_themes = SortedManyToManyField(Domain, limit_choices_to={'school_period':Domain.DOMAIN_PERIOD_DICT[u'Primaire']}, related_name="primary_themes_datasheets")
    college_themes = SortedManyToManyField(Domain, limit_choices_to={'school_period':Domain.DOMAIN_PERIOD_DICT[u'Collège']}, related_name="college_themes_datasheets")
    highschool_themes = SortedManyToManyField(Domain, limit_choices_to={'school_period':Domain.DOMAIN_PERIOD_DICT[u'Lycée']}, related_name="highschool_themes_datasheets")
    town = models.ForeignKey(Location, null=True, blank=True)
    format = models.ForeignKey(DocumentFormat, null=True, blank=True)
    original_creation_date = models.DateField()
    original_modification_date = models.DateField()
    modification_datetime = models.DateTimeField(auto_now=True)
    validation_date = models.DateTimeField(null=True, blank=True)
    validated = models.BooleanField(default=False, db_index=True)
    validator = models.ForeignKey(User, null=True, blank=True)
    manual_order = models.BooleanField(default=False, db_index=True)
    tags = models.ManyToManyField(Tag, through='TaggedSheet')
    
    
    def validate(self, user):
        self.validation_date = datetime.datetime.now()
        self.validated = True
        self.validator = user
        self.save()
    
    def unvalidate(self):
        self.validation_date = datetime.datetime.min
        self.validated = False
        self.validator = None
        self.save()

    @Property
    def domains_list(): #@NoSelf
        def fget(self):
            return [d.label for d in self.domains.all()]
        
        return locals() 

    @Property
    def domains_text(): #@NoSelf
        def fget(self):
            return "; ".join(self.domains_list)
        
        return locals() 

    @Property
    def primary_periods_list(): #@NoSelf
        def fget(self):
            return [d.label for d in self.primary_periods.all()] 

        return locals() 

    
    @Property
    def primary_periods_text(): #@NoSelf
        def fget(self):
            return "; ".join(self.primary_periods_list) 

        return locals() 

    @Property
    def college_periods_list(): #@NoSelf
        def fget(self):
            return [d.label for d in self.college_periods.all()] 

        return locals() 

    @Property
    def college_periods_text(): #@NoSelf
        def fget(self):
            return "; ".join(self.college_periods_list) 

        return locals() 

    @Property
    def highschool_periods_list(): #@NoSelf
        def fget(self):
            return [d.label for d in self.highschool_periods.all()] 

        return locals() 

    @Property
    def highschool_periods_text(): #@NoSelf
        def fget(self):
            return "; ".join(self.highschool_periods_list) 

        return locals() 


    @Property
    def primary_themes_list(): #@NoSelf
        def fget(self):
            return [d.label for d in self.primary_themes.all()] 

        return locals() 


    @Property
    def primary_themes_text(): #@NoSelf
        def fget(self):
            return "; ".join(self.primary_themes_list) 

        return locals() 

    @Property
    def college_themes_list(): #@NoSelf
        def fget(self):
            return [d.label for d in self.college_themes.all()] 

        return locals() 
    
    @Property
    def college_themes_text(): #@NoSelf
        def fget(self):
            return "; ".join(self.college_themes_list) 

        return locals() 

    @Property
    def highschool_themes_list(): #@NoSelf
        def fget(self):
            return [d.label for d in self.highschool_themes.all()] 

        return locals()

    @Property
    def highschool_themes_text(): #@NoSelf
        def fget(self):
            return "; ".join(self.highschool_themes_list) 

        return locals()

    @Property
    def town_text(): #@NoSelf
        def fget(self):
            return self.town.name if self.town else ""
        
        return locals()

    @Property
    def tags_text(): #@NoSelf
        def fget(self):
            return "; ".join([t.label for t in self.tags.all()])
        
        return locals()


class TaggedSheet(models.Model):
    datasheet = models.ForeignKey(Datasheet)
    tag = models.ForeignKey(Tag)
    original_order = models.IntegerField(null=False, blank=False, default=0)
    order = models.IntegerField(null=False, blank=False, default=0, db_index=True)
    index_note = models.FloatField(null=False, blank=False, default=0.0, db_index=True)
    
    
