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

from openerp import models, api, fields, _
from datetime import datetime
from openerp.exceptions import ValidationError
import json


class project_task_activity(models.Model):
    _name = 'project.task.activity'
    _order = "sequence"

    task_id = fields.Many2one(
        'project.task',
        string='Task',
        required=True, ondelete='cascade')
    project_id = fields.Many2one(
        'project.project',
        string='Project',
        related='task_id.project_id', store=True)
    company_id = fields.Many2one(
        'res.company',
        string='Compañía',
        related='task_id.company_id', readonly=True, store=True)
    name = fields.Char('Name', required=True)
    user_id = fields.Many2one('res.users', 'Responsible')
    planned_date = fields.Datetime('Fecha Inicial',default=datetime.today())
    done_date = fields.Datetime('Fecha Final')
    duration= fields.Char(compute='_get_duration', string='Duracion')
    description = fields.Text('Description')
    sequence = fields.Integer(
        'Sequence',
        help="Gives the sequence order when selecting an activitiy.",
        default=10)
    is_done = fields.Boolean('Done?')
    state= fields.Selection(
        [('pending', 'Pendiente'), ('done', 'Realizado'), ('cancel', 'Cancelado')],
        'State', required=True)
    hex_value=fields.Char(string='Color', compute='_get_state_value')

    _defaults = {
        'user_id': lambda obj, cr, uid, ctx=None: uid,
        'state':'pending',
        'hex_value': '#FA5858',
    }

    @api.multi
    @api.onchange('state')
    def _get_state_value(self):
        for record in self:
            if record.state=='pending':
                record.hex_value='#FA5858'

            if record.state=='done':
                record.hex_value='#58ACFA'

            if record.state=='cancel':
                record.hex_value='#A4A4A4'

    @api.multi
    def unlink(self):
        res = super(project_task_activity,self).unlink()
        #  res= self.env.cr.execute("DELETE FROM project_task_activity  WHERE id= %s" % (self.id))
        return res

    @api.onchange('done_date')
    def _get_duration(self):
        res={}
    	if self.done_date and self.planned_date:
            d1 = datetime.strptime(self.planned_date, "%Y-%m-%d %H:%M:%S")
            d2 = datetime.strptime(self.done_date, "%Y-%m-%d %H:%M:%S")
            if d2<d1:
                raise ValidationError('La fecha final no puede ser menor que la fecha de inicio')
            else:
                x = str(d2-d1)
                self.duration=x
                res={'duration':self.duration}
        return {'value':res}


    @api.one
    def action_done(self):
        if self.state == 'pending':
            self.state = 'done'
            self.done_date = datetime.today()
            self.hex_value='#58ACFA'
        else:
            self.state = 'pending'
            self.done_date = False
            self.hex_value='#FA5858'

    @api.one
    def action_cancel(self):
        self.state = 'cancel'
        self.hex_value='#A4A4A4'


class project_task(models.Model):
    _inherit = 'project.task'

    activity_ids = fields.One2many(
        'project.task.activity', 'task_id', 'Activity', copy=True)
    activities_progress = fields.Char(
        string=_("Progress"),
        compute='_get_activities_progress')


    @api.one
    @api.depends('activity_ids.state')
    def _get_activities_progress(self):
        res = []
        for activity in self.activity_ids:
            if activity.state == 'done':
                res.insert(0, {'tooltip': activity.name, 'value': 1})
            elif activity.state != 'cancel':
                res.insert(0, {'tooltip': activity.name, 'value': 0})
        self.activities_progress = json.dumps(res)


class project(models.Model):
    _inherit = 'project.project'

    activity_ids = fields.One2many(
        'project.task.activity',
        string='Activity', compute='_get_task_activity')
    activities_todo = fields.Float(
        string='Activities to do', compute='_get_activities_todo')
    activities_done = fields.Float(
        string='Activities done', compute='_get_activities_done')
    progress_activities = fields.Float(
        string=_("Progress"),
        compute='_get_progress_activities')

    @api.one
    def _get_task_activity(self):
        self.activity_ids = self.env['project.task.activity'].search(
            [('project_id', '=', self.id)])

    @api.one
    def _get_activities_todo(self):
        self.activities_todo = len(
            self.activity_ids.filtered(lambda x: x.state != 'cancel'))

    @api.one
    def _get_activities_done(self):
        self.activities_done = len(
            self.activity_ids.filtered(lambda x: x.state == 'done'))

    @api.one
    def _get_progress_activities(self):
        self.progress_activities = 0
        if self.activity_ids:
            if self.activities_todo != 0:
                self.progress_activities = round(
                    100 * (self.activities_done / self.activities_todo), 1)

    @api.model
    def create(self, vals):

        vals['type'] = 'template'
        print vals

        project_id = super(project, self).create(vals)
        return project_id


class project_category(models.Model):
    _inherit = 'project.category'

    hex_value=fields.Char(string='Color')
