# -*- encoding: UTF-8 -*-

from core.models import UserProfile
from core.ws_utils import CachedWS as ws
from cvn import settings as st_cvn
from django.conf import settings as st
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils.translation import ugettext_lazy as _
from managers import StatsManager, ProfessionalCategoryManager


class Stats(models.Model):
    name = models.CharField(_(u'Nombre'), max_length=40, unique=True)
    code = models.CharField(_(u'Código unidad'), max_length=10)
    number_valid_cvn = models.IntegerField(_(u'CVN válidos'))
    computable_members = models.IntegerField(_(u'Miembros computables'))
    total_members = models.IntegerField(_(u'Miembros totales'))
    percentage = models.DecimalField(_(u'Porcentaje CVN válidos'),
                                     max_digits=5, decimal_places=2)
    objects = StatsManager()

    def update(self, name, members, commit=False):
        self.name = name
        num_cvn_update = 0
        num_computable_members = 0
        for member in members:
            try:
                if ProfessionalCategory.objects.get(
                        code=member['cod_cce']).is_cvn_required is True:
                    num_computable_members += 1
                    user = UserProfile.objects.get(
                        rrhh_code=member['cod_persona'])
                    if user.cvn.status == st_cvn.CVNStatus.UPDATED:
                        num_cvn_update += 1
            except ObjectDoesNotExist:
                pass
        self.total_members = len(members)
        self.computable_members = num_computable_members
        self.number_valid_cvn = num_cvn_update
        try:
            self.percentage = num_cvn_update * 100.0 / num_computable_members
        except ZeroDivisionError:  # Departments with zero computable members
            self.percentage = 100
        if commit:
            self.save()

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['name']
        abstract = True


class Department(Stats):

    @staticmethod
    def get_user_department(rrhh_code):
        if rrhh_code is None:
            return None, None
        try:
            dept_json = ws.get(st.WS_DEPARTMENTS_AND_MEMBERS_USER % rrhh_code)
            if dept_json is None:
                return None, None
            dept_json = dept_json.pop()
            dept = Department.objects.get(
                code=dept_json['unidad']['codigo'])
        except (KeyError, ObjectDoesNotExist):
            return None, None
        return dept, dept_json


class Area(Stats):
    pass


class ProfessionalCategory(models.Model):
    code = models.CharField(_(u'Código de categoría'), max_length=10,
                            unique=True)
    name = models.CharField(_(u'Categoría'), max_length=255)
    is_cvn_required = models.NullBooleanField(_(u'CVN requerido'))
    objects = ProfessionalCategoryManager()

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name_plural = _(u'Professional categories')

@@ -2202,33 +2202,16 @@
 e, None%0A
-        try:%0A    
         
@@ -2285,20 +2285,16 @@
         
-   
- 
 if dept_
@@ -2299,36 +2299,32 @@
 t_json is None:%0A
-    
             retu
@@ -2341,28 +2341,24 @@
 one%0A        
-    
 dept_json = 
@@ -2385,42 +2385,96 @@
     
-    dept = Department.objects.get(
+if 'unidad' in dept_json and not len(dept_json%5B'unidad'%5D):%0A            return None, None
 %0A   
@@ -2474,32 +2474,37 @@
 one%0A        
+try:%0A
         
 code=dept_js
@@ -2487,24 +2487,58 @@
 ry:%0A        
+    dept = Department.objects.get(
 code=dept_js

Call WS with an user type PAS