from odoo import api, fields, models
from odoo.exceptions import UserError, AccessError, ValidationError
from datetime import datetime
from dateutil import relativedelta


class ProjectResourceWizard(models.TransientModel):
    _name = 'project.resource.wizard'

    @api.model
    def default_get(self, fields):
        res = super(ProjectResourceWizard, self).default_get(fields)
        res_id = self._context.get('active_id')
        record = self.env['project.project'].browse(res_id)
        lines = []
        emp_id = []
        for rec in record.sale_line_employee_ids:
            resource_rec = {}
            if rec.employee_id and rec.employee_id.id not in emp_id:
                emp_id.append(rec.employee_id.id)
                resource_rec.update({'employee_id':rec.employee_id.id, 'project_id': res_id, 'employee_price': rec.employee_id.timesheet_cost})
                lines.append((0, 0, resource_rec))
        res.update({'add_project_resource': lines})
        return res

    project_id = fields.Many2one('project.project')
    add_project_resource = fields.One2many('project.resource.line', 'wizard_id')


    def action_add_project_lines(self):
        record = self.env['project.sale.line.employee.map']
        for val in self.add_project_resource:
            values = {
                'project_id': self.project_id.id,
                'employee_id': val.employee_id.id,
                'role': val.role,
                'start_date': val.start_date,
                'end_date': val.end_date,
                'price_unit': val.price_unit,
                'budgeted_qty': val.budgeted_qty,
                'cost': val.cost,
                'employee_price': val.employee_price,
            }
            if self.project_id.hour_distribution == 'Percentage':
                values.update({'distribution_per': val.distribution_per})
            record.create(values)
        return True

class ProjectResourceLine(models.Model):
    _name = "project.resource.line"
    _description = "Project Resource Line"

    wizard_id = fields.Integer()
    project_id = fields.Many2one('project.project')
    employee_id = fields.Many2one('hr.employee')
    role = fields.Selection([('Manager', 'Manager'),('Employee', 'Employee'), ], string="Role", default="Employee")
    start_date = fields.Date(required=True)
    end_date = fields.Date(required=True)
    price_unit = fields.Float("Hourly Rate")
    budgeted_qty = fields.Float(string='Bud. Hours', digits=(16, 2))
    cost = fields.Float("Bud. Revenue", default=0.0)
    employee_price = fields.Float(string="Cons. Price")
    hour_distribution = fields.Selection(related='project_id.hour_distribution')
    distribution_per = fields.Float("%")

    @api.onchange('employee_id')
    def onchange_employee_price(self):
        if self.employee_id:
            self.employee_price = self.employee_id.timesheet_cost
        else:
            self.employee_price = 0.0

    @api.onchange('price_unit', 'budgeted_qty')
    def _calculate_total_cost(self):
        #if self.env.context.get('active_model') == 'project.project' and self.env.context.get('active_id'):
        #pro = self.env['project.project'].browse(self.env.context.get('active_id'))
        if self.project_id.project_type == 'hours_in_consultant':
            if self.hour_distribution == 'Manual':
                self.cost = self.price_unit * self.budgeted_qty

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