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

from core.ws_utils import CachedWS as ws
from cvn.models import (Articulo, Libro, Capitulo, Congreso, Proyecto,
                        Convenio, TesisDoctoral)
from core.models import UserProfile
from cvn.utils import isdigit
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings as st
from informe_pdf import InformePDF
from informe_csv import Informe_csv
from optparse import make_option
from django.core.exceptions import ObjectDoesNotExist


class Command(BaseCommand):
    help = u'Genera un PDF/CSV con los datos de un Departamento/Area'
    option_list = BaseCommand.option_list + (
        make_option(
            "-y",
            "--year",
            dest="year",
            help="Specify the year in format YYYY",
        ),
        make_option(
            "-i",
            "--id",
            dest="id",
            help="Specify the ID of the Department/Area",
        ),
        make_option(
            "-t",
            "--type",
            dest="type",
            default='d',
            help="Specify the type of filtering: d (department) or a (area)",
        ),
        make_option(
            "-f",
            "--format",
            dest="format",
            default='pdf',
            help="Specify the output format",
        ),
    )

    def handle(self, *args, **options):
        self.check_args(options)
        year = int(options['year'])
        unit_id = [int(options['id'])] if type(options['id']) is str else None
        model = None
        if options['type'] == 'a':
            # model = GrupoinvestAreaconocimiento
            self.model_type = 'area'
        else:
            self.model_type = 'department'
            self.codigo = 'cod_departamento'
        if options['format'] == 'pdf':
            self.generator = InformePDF
        else:
            self.generator = Informe_csv
        self.create_reports(year, unit_id, model)

    def check_args(self, options):
        if not isdigit(options['year']):
            raise CommandError(
                "Option `--year=YYYY` must exist and be a number")
        if (not isdigit(options['id'])) and options['id'] is not None:
            raise CommandError("Option `--id=X` must be a number")
        if not options['type'] == 'a' and not options['type'] == 'd':
            raise CommandError("Option `--type=X` must be a (area) "
                               "or d (department)")
        if not options['format'] == 'pdf' and not options['format'] == 'csv':
            raise CommandError("Option `--format=X` must be pdf or csv")

    def create_reports(self, year, unit_id, model):
        if unit_id is None:
            if self.model_type == 'department':
                units = ws.get(st.WS_DEPARTMENTS_YEAR % year)
                if units is None:
                    raise IOError(
                        'WS "%s" does not work' % st.WS_DEPARTMENTS_YEAR % year)
            else:
                units = model.objects.all()
            for unit in units:
                self.create_report(year, unit)
        else:
            for code in unit_id:
                unit = ws.get(st.WS_DEPARTMENT_YEAR % (code, year))
                self.create_report(year, unit[0])

    def create_report(self, year, unit):
        (investigadores, articulos,
         libros, capitulos_libro, congresos, proyectos,
         convenios, tesis) = self.get_data(year, unit)
        print 'Generando Informe para [%s] %s ... ' % (
            unit['unidad']['codigo'], unit['unidad']['nombre'])
        if investigadores:
            informe = self.generator(year, unit['unidad'], investigadores,
                                     articulos, libros, capitulos_libro,
                                     congresos, proyectos, convenios, tesis,
                                     self.model_type)
            informe.go()
            print 'OK\n'
        else:
            print 'ERROR: No hay Investigadores\n'

    def get_data(self, year, unit):
        investigadores, usuarios = self.get_investigadores(unit)
        articulos = Articulo.objects.byUsuariosYear(usuarios, year)
        libros = Libro.objects.byUsuariosYear(usuarios, year)
        capitulos_libro = Capitulo.objects.byUsuariosYear(usuarios, year)
        congresos = Congreso.objects.byUsuariosYear(usuarios, year)
        proyectos = Proyecto.objects.byUsuariosYear(usuarios, year)
        convenios = Convenio.objects.byUsuariosYear(usuarios, year)
        tesis = TesisDoctoral.objects.byUsuariosYear(usuarios, year)
        return (investigadores, articulos,
                libros, capitulos_libro, congresos, proyectos,
                convenios, tesis)

    def get_investigadores(self, unit):
        investigadores = list()
        usuarios = list()
        for inv in unit['miembros']:
            inv = self.check_inves(inv)
            investigadores.append(inv)
            try:
                user = UserProfile.objects.get(rrhh_code=inv['cod_persona'])
                usuarios.append(user)
            except ObjectDoesNotExist:
                pass
        return investigadores, usuarios

    def check_inves(self, inv):
        if 'cod_persona__nombre' not in inv:
            inv['cod_persona__nombre'] = ''
        if 'cod_persona__apellido1' not in inv:
            inv['cod_persona__apellido1'] = ''
        if 'cod_persona__apellido2' not in inv:
            inv['cod_persona__apellido2'] = ''
        if 'cod_cce__descripcion' not in inv:
            inv['cod_cce_descripcion'] = ''
        return inv

@@ -20,16 +20,52 @@
 -8 -*-%0A%0A
+from core.models import UserProfile%0A
 from cor
@@ -167,16 +167,26 @@
 royecto,
+ Convenio,
 %0A       
@@ -201,26 +201,16 @@
         
- Convenio,
  TesisDo
@@ -219,32 +219,30 @@
 oral)%0Afrom c
-ore.mode
+vn.uti
 ls import Us
@@ -243,48 +243,107 @@
 ort 
-UserProfile%0Afrom cvn.utils import isdigi
+isdigit%0Afrom django.conf import settings as st%0Afrom django.core.exceptions import ObjectDoesNotExis
 t%0Afr
@@ -410,47 +410,8 @@
 ror%0A
-from django.conf import settings as st%0A
 from
@@ -419,19 +419,19 @@
 informe_
-pdf
+csv
  import 
@@ -437,19 +437,20 @@
  Informe
-PDF
+_csv
 %0Afrom in
@@ -447,35 +447,35 @@
 sv%0Afrom informe_
-csv
+pdf
  import Informe_
@@ -469,28 +469,27 @@
 port Informe
-_csv
+PDF
 %0Afrom optpar
@@ -514,62 +514,8 @@
 ion%0A
-from django.core.exceptions import ObjectDoesNotExist%0A
 %0A%0Acl

Clean Code