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

# Copyright (C) 2012 Rodrigo Alves Lima
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import datetime
import os

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

from src.settings import MEDIA_URL
from src.utils import random_str


UNIVERSITY_CHOICES = (
    ('USP', 'Universidade de São Paulo'),
)

FACULTY_CHOICES = (
    ('IME', 'Instituto de Matemática e Estatística'),
    ('POLI', 'Escola Politécnica'),
    ('FEA', 'Faculdade de Economia e Administração'),
    ('IQ', 'Instituto de Química'),
)

class Ask(models.Model):
    code = models.CharField(max_length=128)
    username = models.EmailField(unique=True)

    def __unicode__(self):
        return self.username

    def save(self, *args, **kwargs):
        self.code = random_str(128)
        super(Ask, self).save(*args, **kwargs)

def image_filename(profile, filename):
    return os.path.join(
        'account/profile/image/',
        random_str(32) + os.path.splitext(filename)[1].lower()
    )

class Profile(models.Model):
    user = models.OneToOneField(User)
    birthday = models.DateField()
    university = models.CharField(
        max_length=32,
        choices=UNIVERSITY_CHOICES,
        default='USP'
    )
    faculty = models.CharField(
        max_length=128,
        choices=FACULTY_CHOICES,
        default='IME'
    )
    image = models.ImageField(upload_to=image_filename)

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

    def image_url(self):
        return MEDIA_URL + str(self.image)

def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance, birthday=datetime.date.today())

def delete_ask(sender, instance, created, **kwargs):
    if created:
        Ask.objects.filter(username=instance.user.username).delete()

post_save.connect(create_profile, sender=User)
post_save.connect(delete_ask, sender=Profile)
