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")
    allow_to_create = fields.Selection(selection=[('always', 'Always'), ('specific', 'Specific')] )
    permission_history = fields.One2many(comodel_name="timesheet.block.history", inverse_name="employee_id",
                                         string="History", required=False )

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

    allow_to_edit = fields.Selection(selection=[('always', 'Always'), ('specific', 'Specific')],string="Allow to edit")
    allow_to_create = fields.Selection(selection=[('always', 'Always'), ('specific', 'Specific')] )
    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'

    start_date = fields.Date('Start Date')
    end_date = fields.Date('End 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()
        config = self.env['ir.config_parameter'].sudo()
        config_days_limit = float(config.get_param('timesheet_block.timesheet_edit_create_limit'))
        entry_start_date = datetime.strptime(str(values['start_datetime']),"%Y-%m-%d %H:%M:%S").date()
        # entry_end_date = datetime.strptime(values['end_datetime'],"%Y-%m-%d %H:%M:%S").date()
        days = (current_date - entry_start_date).days
        employee_object = self.env['hr.employee'].search([('user_id', '=', self.env.uid)])
        project_manager_group = self.env.ref('hr_timesheet.group_timesheet_manager')
        if self.env.uid not in project_manager_group.users.ids:
            if days >= config_days_limit:
                if employee_object.allow_to_create != 'always' or employee_object.allow_to_create == False:
                    permission_object = employee_object.permission_history.search([('permission_type', '=', 'create'),('employee_id', '=', employee_object.id)] , order='create_date desc' , limit = 1)
                    if permission_object:
                        # if not (permission_object.start_date <= entry_start_date and permission_object.end_date >= entry_start_date) or not (permission_object.start_date <= entry_end_date and permission_object.end_date >= entry_end_date):
                        if not (permission_object.start_date <= entry_start_date and permission_object.end_date >= entry_start_date):
                            raise AccessError('You can not create the backdate entry please contact to HR')
                    else:
                        raise AccessError('You can not create the backdate entry please contact to HR')
        return super(TimehseetBlock, self).create(values)


    def write(self, record):
        current_date = datetime.today().date()
        if 'start_datetime' in record or 'end_datetime' in record or 'project_id' in record or 'sub_project' in record or 'task_id' in record or 'description' in record:
            if 'start_datetime' in record:
                entry_start_date = datetime.strptime(str(record['start_datetime']),"%Y-%m-%d %H:%M:%S").date()
                # entry_end_date = datetime.strptime(record['end_datetime'],"%Y-%m-%d %H:%M:%S").date()
            else:
                res_start_date = str(self.start_datetime).split('.', 1)[0]
                # res_end_date = str(self.end_datetime).split('.', 1)[0]
                entry_start_date = datetime.strptime(str(res_start_date), '%Y-%m-%d %H:%M:%S').date()
                # entry_end_date = datetime.strptime(str(res_end_date), '%Y-%m-%d %H:%M:%S').date()

            if current_date != entry_start_date:
                employee_object = self.env['hr.employee'].search([('user_id', '=', self.env.uid)])
                if employee_object.allow_to_edit != 'always' or employee_object.allow_to_edit == False:
                    permission_object = employee_object.permission_history.search([('permission_type', '=', 'edit'),('employee_id', '=', employee_object.id)], order='create_date desc' , limit = 1)
                    if self.user_id.id == self.env.uid:
                        if permission_object:
                            # if not (permission_object.start_date <= entry_start_date and permission_object.end_date >= entry_start_date) or not (permission_object.start_date <= entry_end_date and permission_object.end_date >= entry_end_date):
                            if not (permission_object.start_date <= entry_start_date and permission_object.end_date >= entry_start_date):
                                raise AccessError(
                                    'You can not edit your backdate entry please connect to HR/Department Head/Project Manager')
                        else:
                            raise AccessError(
                                'You can not edit your backdate entry please connect to HR/Department Head/Project Manager')
        return super(TimehseetBlock, self).write(record)



    # @api.onchange('end_datetime' ,'start_datetime')
    # def _check_end_datetime(self):
    #     if self.end_datetime and self.start_datetime:
    #         current_date = datetime.today().date()
    #         end_date = datetime.strptime(str(self.end_datetime), "%Y-%m-%d %H:%M:%S").date()
    #         start_date = datetime.strptime(str(self.start_datetime), "%Y-%m-%d %H:%M:%S").date()
    #         if end_date > current_date:
    #             self.end_datetime = False
    #             self.start_datetime = False
    #             raise AccessError('End date cannot be a future date!')
    #         if start_date > end_date:
    #             self.end_datetime = False
    #             self.start_datetime = False
    #             raise AccessError('End date should be greater than start date!')

    @api.constrains('unit_amount')
    def _check_unit_amount(self):
        for rec in self:
            if rec.unit_amount < 0.0:
                raise AccessError('End date should be greater than start date!')

    @api.constrains('end_datetime')
    def _check_end_datetime(self):
        current_date = datetime.today().date()
        for rec in self:
            if rec.end_datetime:
                end_date = datetime.strptime(str(self.end_datetime), "%Y-%m-%d %H:%M:%S").date()
                if end_date > current_date:
                    raise AccessError('End date cannot be a future date!')

