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'

    permission_block_history = fields.One2many(comodel_name="timesheet.block.history", inverse_name="employee_id",
                                               string="History", required=False)


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

    permission_block_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')
    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):
        format = "%Y-%m-%d %H:%M:%S"
        entry_start_date = datetime.strptime(str(values['start_datetime']), format).date()
        entry_end_date = datetime.strptime(values['end_datetime'], format).date()
        emp_obj = self.env['hr.employee'].search([('user_id', '=', self.env.uid)])
        # project_manager_group = self.env.ref('hr_timesheet.group_timesheet_manager')
        block_obj = emp_obj.permission_block_history.search([('employee_id', '=', emp_obj.id)], order='create_date desc', limit=1)
        if block_obj:
            if (block_obj.start_date <= entry_start_date and block_obj.end_date >= entry_start_date) or (
                    block_obj.start_date <= entry_end_date and block_obj.end_date >= entry_end_date) or (
                    block_obj.start_date >= entry_start_date and block_obj.end_date <= entry_end_date
            ) or (
                    block_obj.end_date >= entry_start_date and block_obj.end_date <= entry_end_date
            ):
                raise AccessError('You are not allowed to create entry for this date!')
        return super(TimehseetBlock, self).create(values)

    def write(self, record):
        format = "%Y-%m-%d %H:%M:%S"
        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 and 'end_datetime' not in record:
                entry_start_date = datetime.strptime(str(record['start_datetime']), format).date()
                entry_end_date = datetime.strptime(str(self.end_datetime), format).date()
            elif 'start_datetime' not in record and 'end_datetime' in record:
                entry_start_date = datetime.strptime(str(self.start_datetime), format).date()
                entry_end_date = datetime.strptime(str(record['end_datetime']), format).date()
            elif 'start_datetime' in record and 'end_datetime' in record:
                entry_start_date = datetime.strptime(str(record['start_datetime']), format).date()
                entry_end_date = datetime.strptime(str(record['end_datetime']), format).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), format).date()
                entry_end_date = datetime.strptime(str(res_end_date), format).date()
            emp_obj = self.env['hr.employee'].search([('user_id', '=', self.env.uid)])
            # project_manager_group = self.env.ref('hr_timesheet.group_timesheet_manager')
            if self.user_id.id == self.env.uid:
                block_obj = emp_obj.permission_block_history.search(
                    [('employee_id', '=', emp_obj.id)], order='create_date desc', limit=1)
                if block_obj:
                    if (block_obj.start_date <= entry_start_date and block_obj.end_date >= entry_start_date) or (
                            block_obj.start_date <= entry_end_date and block_obj.end_date >= entry_end_date) or (
                            block_obj.start_date >= entry_start_date and block_obj.end_date <= entry_end_date) or (
                            block_obj.end_date >= entry_start_date and block_obj.end_date <= entry_end_date):
                        raise AccessError('You are not allowed to edit entry for this date!')
        return super(TimehseetBlock, self).write(record)

    # @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!')
