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

from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
import mptt


class Department(models.Model):
    """
    Department record
    """
    #id = models.PositiveIntegerField(primary_key=True)
    from_staff_id = models.PositiveIntegerField(db_index=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
    name = models.CharField(max_length=255)
    en_name = models.CharField(max_length=255, null=True)
    code = models.CharField(max_length=20, null=True)
    bg_color = models.CharField(max_length=20, null=True)
    fg_color = models.CharField(max_length=20, null=True)

    def __unicode__(self):
        return self.name

    @property
    def chief(self):
        try:
            return self.departmentstaff_set.select_related('staff').filter(role=DepartmentStaff.ROLE_CHIEF)[0].staff
        except IndexError:
            return None

    @property
    def deputy(self):
        try:
            return self.departmentstaff_set.select_related('staff').filter(role=DepartmentStaff.ROLE_DEPUTY)[0].staff
        except IndexError:
            return None


if hasattr(mptt, 'register'):
    try:
       mptt.register(Department)
    except mptt.AlreadyRegistered:
       pass


class DepartmentStaffCounter(models.Model):
    department = models.ForeignKey('Department', null=False)
    day = models.DateField(db_index=True)
    staff_counter = models.PositiveSmallIntegerField()

    def __unicode__(self):
        return '%s at %s: %d' % (self.dep.name, self.day, self.all)


class City(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Office(models.Model):
    """
    Office record
    """
    from_staff_id = models.PositiveIntegerField(db_index=True)
    name = models.CharField(max_length=255)
    city = models.ForeignKey(City, null=True)

    def __unicode__(self):
        return self.name

    def _get_short_name(self):
        if self.name.find(', ') != -1:
            return self.name[self.name.find(', ')+2:]
        return self.name
    short_name = property(_get_short_name)


class StaffManager(models.Manager):

    def get_by_name(self, name):
        import re
        from django.db.models import Q

        nameparts = re.split(r'\s+', name.strip(), 1)
        if len(nameparts) == 2:
            return Staff.objects.get(
                    Q(first_name=nameparts[0], last_name=nameparts[1])
                    | Q(first_name=nameparts[1], last_name=nameparts[0]))
        return None


class Staff(models.Model):
    """
    Staff account record
    """
    #id = models.PositiveIntegerField(primary_key=True)
    from_staff_id = models.PositiveIntegerField(db_index=True)
#    user_id = models.PositiveIntegerField(null=True) # wiki-users

    first_name = models.CharField(max_length=50, null=True, db_index=True)
    middle_name = models.CharField(max_length=50, null=True)
    last_name = models.CharField(max_length=100, null=True, db_index=True)
    en_name = models.CharField(max_length=255, null=True)
    birthday = models.DateField(null=True)
    GENDER_CHOICES = (
        ('M', 'male'),
        ('F', 'female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)
    FAMILY_STATUS_CHOICES = (
        ('S', 'single'),
        ('M', 'marriage'),
    )
    family_status = models.CharField(max_length=1, choices=FAMILY_STATUS_CHOICES, null=True)
    children = models.PositiveSmallIntegerField(null=True)
    car = models.CharField(max_length=100, null=True)
    car_num = models.CharField(max_length=50, null=True)
    address = models.CharField(max_length=255, null=True)
#    about = models.CharField(max_length=1000, null=True)
    EDU_CHOICES = (
        ('S', 'secondary'),
        ('I', 'higher_incomplete'),
        ('T', 'higher_technical'),
        ('L', 'higher_liberal'),
        ('N', 'higher_natural'),
    )
    edu_status = models.CharField(max_length=1, choices=EDU_CHOICES, null=True)
    edu_place = models.CharField(max_length=255, null=True)
    edu_date = models.DateField(null=True)

    department = models.ForeignKey('Department', null=True)
    is_dismissed = models.BooleanField(default=False)
    office = models.ForeignKey('Office', null=True)
    desk_id = models.PositiveIntegerField(null=True)
    login = models.CharField(max_length=50, db_index=True, null=True)
    login_ld = models.CharField(max_length=50, db_index=True, null=True)
    DOMAIN_CHOICES = (
        ('C', 'comptek.ru'),
        ('Y', 'yandex-team.ru'),
        ('U', 'yandex-team.com.ua'),
        ('M', 'yamoney.ru'),
    )
    domain = models.CharField(max_length=1, choices=DOMAIN_CHOICES, null=True)
    wiki_name = models.CharField(max_length=100, db_index=True, null=True)
    join_at = models.DateField(null=True)
    quit_at = models.DateField(null=True)
    position = models.CharField(max_length=100, null=True)
    EMPL_CHOICES = (
        ('F', 'empl_full'),
        ('P', 'empl_part'),
        ('D', 'empl_double'),
    )
    employment = models.CharField(max_length=1, choices=EMPL_CHOICES, null=True)
#    functions = models.CharField(max_length=1000, null=True)
#    work_place = models.CharField(max_length=100)
#    computer = models.CharField(max_length=255, null=True)
    is_big_boss = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    avatar = models.ImageField(upload_to='i/user/')
    photo = models.ImageField(upload_to='i/userphoto/')

    #ex-contacts
    work_phone = models.PositiveIntegerField(null=True, db_index=True)
    mobile_phone = models.CharField(max_length=100, null=True, db_index=True)
    work_email = models.CharField(max_length=100, null=True, db_index=True)

    guid = models.CharField(max_length=47, null=True, default='')

    def __unicode__(self):
        if self.first_name and self.last_name:
            return self.first_name + ' ' + self.last_name
        else:
            return self.login

    @property
    def departments(self):
        """
        Перечень поразделений компании, в которых состоит сотрудник, начиная с департамента
        
        Примеры:
            Staff.objects.get(login='thasonic').departmets => 
        """
        if not self.department:
            return []
        l = list(self.department.get_ancestors(False))
        l.append(self.department)
        return l
#    departments = property(_get_departments)

    objects = StaffManager()


class DepartmentStaff(models.Model):
    ROLE_CHIEF = 'C'
    ROLE_DEPUTY = 'D'
    department = models.ForeignKey('Department', null=True)
    staff = models.ForeignKey('Staff', null=True)
    ROLE_CHOICES = (
        (ROLE_CHIEF, 'chief'),
        (ROLE_DEPUTY, 'deputy'),
    )
    role = models.CharField(max_length=1, choices=ROLE_CHOICES)

    def __unicode__(self):
        return '%s is %s of %s' % (unicode(self.staff), self.get_role_display(), unicode(self.department))


class StaffInflection(models.Model):
#    SUBJECTIVE_CASE = 's'
#    GENITIVE_CASE = 'g'
#    DATIVE_CASE = 'd'
#    ACCUSATIVE_CASE = 'a'
#    ABLATIVE_CASE = 'b'
#    PREPOSITIONAL_CASE = 'p'
#    CASE_CHOICES = (
#        (SUBJECTIVE_CASE, 'именительный'),
#        (GENITIVE_CASE, 'родительный'),
#        (DATIVE_CASE, 'дательный'),
#        (ACCUSATIVE_CASE, 'винительный'),
#        (ABLATIVE_CASE, 'творительный'),
#        (PREPOSITIONAL_CASE, 'предложный'),
#    )

    staff = models.ForeignKey(Staff)
    subjective = models.CharField(max_length=100)
    genitive = models.CharField(max_length=100)
    dative = models.CharField(max_length=100)
    accusative = models.CharField(max_length=100)
    ablative = models.CharField(max_length=100)
    prepositional = models.CharField(max_length=100)

    def __iter__(self):
        yield self.subjective
        yield self.genitive
        yield self.dative
        yield self.accusative
        yield self.ablative
        yield self.prepositional


class Service(models.Model):
    from_staff_id = models.PositiveIntegerField(db_index=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
    jira_key = models.CharField(max_length=20, null=True)
    name = models.CharField(max_length=255)
    url = models.CharField(max_length=255, null=True)
    url_wiki = models.CharField(max_length=255, null=True)
    wiki_supertag = models.CharField(max_length=255, db_index=True, null=True)
    order = models.IntegerField(db_index=True)
    maillist = models.EmailField(null=True)
    owner = models.ForeignKey(Staff, null=True)

if hasattr(mptt, 'register'):
    try:
       mptt.register(Service)
    except mptt.AlreadyRegistered:
       pass

class ServiceRole(models.Model):
    from_staff_id = models.PositiveIntegerField(db_index=True)
    name = models.CharField(max_length=255, null=True)
    order = models.IntegerField(db_index=True)
    senior = models.BooleanField(default=False)


class ServiceMember(models.Model):
    from_staff_id = models.PositiveIntegerField(db_index=True)
    staff = models.ForeignKey(Staff)
    service = models.ForeignKey(Service)
    role = models.ForeignKey(ServiceRole)
    description = models.CharField(max_length=255, null=True)
    order = models.IntegerField(db_index=True)
    is_temp = models.BooleanField(default=False)


    
