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


class EmployeeInherit(models.Model):
    _inherit = 'hr.employee'

    allow_to_edit = fields.Selection(selection=[('always', 'Always'), ('specific', 'Specific')],string="Allow to edit",store=True)
    allow_to_create = fields.Selection(selection=[('always', 'Always'), ('specific', 'Specific')] , store=True)
    permission_history = fields.One2many(comodel_name="timesheet.block.history", inverse_name="employee_id",
                                         string="History", required=False )


class TimesheetBlock(models.Model):
    _name = 'timesheet.block.history'

    date = fields.Date('Date')
    permission_type = fields.Selection(string="Permission Type", selection=[('edit', 'Edit'), ('create', 'Create')],
                                       required=False)
    reason = fields.Text('Reason')
    user_id = fields.Many2one('res.users', string='Given By')
    employee_id = fields.Many2one(comodel_name="hr.employee", string="Employee", required=False)


class TimehseetBlock(models.Model):
    _inherit = 'account.analytic.line'

    @api.model
    def create(self, values):
        current_date = datetime.today().date()
        entry_date = datetime.strptime(values['date'], "%Y-%m-%d").date()
        months_diff = current_date.month - entry_date.month
        employee_object = self.env['hr.employee'].sudo().search([('user_id', '=', self.env.uid)])
        project_manager_group = self.env.ref('hr_timesheet.group_timesheet_manager')
        config = self.env['ir.config_parameter'].sudo()
        config_days_limit = float(config.get_param('timesheet_block.timesheet_edit_create_limit'))
        if entry_date <= current_date:
            if self.env.uid not in project_manager_group.users.ids:
                if months_diff == 0:
                    res = super(TimehseetBlock, self).create(values)
                elif months_diff == 1:
                    if employee_object.allow_to_create == 'always' and current_date.day <= config_days_limit:
                        res = super(TimehseetBlock, self).create(values)
                    else:
                        raise AccessError('You can not create your backdate entry please connect to Hr/Department Head')
                else:
                    raise AccessError('You can not create your backdate entry please connect to Hr/Department Head')
            else:
                res = super(TimehseetBlock, self).create(values)
        else:
            raise AccessError('You can not create future entry')
        return res


    def write(self, values):
        current_date = datetime.today().date()
        if 'date' in values:
            entry_date = datetime.strptime(values['date'], "%Y-%m-%d").date()
        else:
            res_date = str(self.date).split('.', 1)[0]
            entry_date = datetime.strptime(str(res_date), '%Y-%m-%d %H:%M:%S').date()
        months_diff = current_date.month - entry_date.month
        employee_object = self.env['hr.employee'].sudo().search([('user_id', '=', self.env.uid)])
        project_manager_group = self.env.ref('hr_timesheet.group_timesheet_manager')
        config = self.env['ir.config_parameter'].sudo()
        config_days_limit = float(config.get_param('timesheet_block.timesheet_edit_create_limit'))
        if self.env.uid not in project_manager_group.users.ids:
            if months_diff == 0:
                res = super(TimehseetBlock, self).write(values)
            elif months_diff == 1:
                if employee_object.allow_to_edit == 'always' and current_date.day <= config_days_limit:
                    res = super(TimehseetBlock, self).write(values)
                else:
                    raise AccessError('You can not edit your backdate entry please connect to Hr/Department Head')
            else:
                raise AccessError('You can not edit your backdate entry please connect to Hr/Department Head')
        else:
            res = super(TimehseetBlock, self).write(values)
        return res
