# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from dateutil.relativedelta import relativedelta

class ProjectMultiBudgetAssign(models.TransientModel):
    _name = 'project.multi.budget.assign'
    _description = 'Project multi budget assign'

    project_id = fields.Many2one('project.project', string="Project", required=True)
    project_start_date = fields.Date('Project Start Date', related='project_id.date_start')
    project_end_date = fields.Date('Project End Date', related='project_id.date')
    start_date = fields.Date('Start Date', required=True, default=fields.Date.context_today)
    end_date = fields.Date('End Date', required=True)
    project_multi_line = fields.One2many('project.multi.budget.assign.line', 'line_id', 'Consultant Details')

    @api.model
    def default_get(self, fields):
        res = super(ProjectMultiBudgetAssign, self).default_get(fields)
        res_id = self._context.get('active_id')
        record = self.env['project.project'].browse(res_id)
        lines = []
        for rec in record.sale_line_employee_ids:
            cons = {}
            all_cons = self.env['project.consultant.hrs'].search([('employee_id','=',rec.employee_id.id),('project_id','=',rec.project_id.id)])
            all_per = [v.percentage for v in all_cons]
            if sum(all_per) < 100:
                cons.update({'employee_id': rec.employee_id.id, 'emp_map_id':rec.id, 'project_id':res_id})
                lines.append((0, 0, cons))
        if record and (not record.pricing_type == 'employee_rate' or not record.project_type == 'hours_in_consultant'):
            raise ValidationError(_('Not applicable for this project type '))
        if not lines:
            raise ValidationError(_('Not applicable, Please assign or check consultant'))
        if record and not record.date_start or not record.date:
            raise UserError(_('Project start date and end date should not be blank'))
        res.update({'project_id':res_id, 'project_multi_line': lines})
        return res

    @api.constrains('start_date', 'end_date')
    def _check_dates(self):
        for rec in self:
            if rec.end_date < rec.start_date:
                raise ValidationError(_('Start date must be earlier than end date.'))

    @api.onchange('start_date')
    def onchange_start_date(self):
        if self.start_date:
            self.end_date = self.start_date + relativedelta(days=6)

    def action_create_budgeted_hrs(self):
        record = self.env['project.consultant.hrs']
        res_id = self._context.get('active_id')
        for val in self:
            for line in val.project_multi_line:
                record.create({'project_id':res_id,
                               'employee_id':line.employee_id.id,
                               'start_date':val.start_date,
                               'end_date':val.end_date,
                               'budgeted_hours':line.budgeted_hours,
                               'percentage':line.percentage})
        return True


class ProjectMultiBudgetAssignLine(models.TransientModel):
    _name = 'project.multi.budget.assign.line'
    _description = 'Project multi budget assign line'

    """domain = lambda self: self._get_employee_id_domain(),
    @api.model
    def _get_employee_id_domain(self):
        project_id = self._context.get('active_id')
        record = self.env['project.project'].browse(project_id)
        emp_ids = [emp.employee_id.id for emp in record.sale_line_employee_ids]
        return [('id','in', emp_ids)]"""

    line_id = fields.Many2one('project.multi.budget.assign', string="Line ID", required=True)
    project_id = fields.Many2one('project.project', string="Project", required=True)
    emp_map_id = fields.Many2one('project.sale.line.employee.map', string="Consultant Map", required=True)
    employee_id = fields.Many2one('hr.employee', string="Consultant",  required=True)
    budgeted_qty = fields.Float(string='Budgeted Hours', related="emp_map_id.budgeted_qty")
    all_percentage = fields.Float("Total Allocated %", compute='_compute_allocation')
    rem_percentage = fields.Float("Total Unallocated %", compute='_compute_allocation')
    percentage = fields.Float("Percentage %")
    remaining = fields.Float("Remaining Percentage %")
    budgeted_hours = fields.Float("Budgeted Hours for period", compute='_compute_budgeted_hours', store=True)

    @api.onchange('percentage')
    def onchange_employee_id(self):
        res = self.rem_percentage - self.percentage
        if res < 0:
            raise ValidationError(_('Remaining percentage should not be negative'))
        self.remaining = res

    @api.depends('project_id', 'employee_id')
    def _compute_allocation(self):
        for val in self:
            if val.project_id and val.employee_id:
                cons = self.env['project.consultant.hrs'].search([('employee_id','=',val.employee_id.id),('project_id','=',val.project_id.id)])
                all_per = 0
                for res in cons:
                    all_per += res.percentage
                #res =  all_per - 100
                val.all_percentage = all_per
                val.rem_percentage = 100 - all_per
                val.remaining = 100 - all_per
            else:
                val.all_percentage = 0
                val.rem_percentage = 0
                val.remaining = 0

    @api.depends('project_id', 'employee_id', 'project_id.sale_line_employee_ids', 'percentage')
    def _compute_budgeted_hours(self):
        for val in self:
            if val.project_id and val.employee_id and val.percentage > 0:
                budgeted = 0
                for emp in val.project_id.sale_line_employee_ids:
                    if emp.employee_id.id == val.employee_id.id:
                        budgeted = emp.budgeted_qty
                val.budgeted_hours = (budgeted * val.percentage / 100)
            else:
                val.budgeted_hours = 0

    """@api.onchange('employee_id', 'percentage')
    def onchange_employee_id(self):
        #res = {}
        project_id = self._context.get('active_id')
        record = self.env['project.project'].browse(project_id)
        #emp_ids = [emp.employee_id.id for emp in record.sale_line_employee_ids]
        #res['domain'] = {'employee_id': [('id', 'in', emp_ids)]}
        if self.employee_id and self.percentage > 0:
            print("self.employee_id", self.employee_id)
            cons = [emp.budgeted_qty if emp.employee_id.id == self.employee_id.id else 0 for emp in record.sale_line_employee_ids]
            budgeted = cons and cons[0] or 0
            if budgeted > 0:
                self.budgeted_hours = (budgeted * self.percentage / 100)
            else:
                self.budgeted_hours = 0"""
        #return res