# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import models, fields, api


class ResourceCalendarAttendance(models.Model):
    _inherit = 'resource.calendar.attendance'

    work_entry_type_id = fields.Many2one(
        'hr.work.entry.type', 'Work Entry Type', groups="hr.group_hr_user",
        domain="[('id', 'in', allowed_work_entry_type_ids)]")
    allowed_work_entry_type_ids = fields.Many2many(
        'hr.work.entry.type', compute='_compute_allowed_work_entry_type_ids')

    @api.depends('calendar_id.company_id')
    def _compute_allowed_work_entry_type_ids(self):
        for attendance in self:
            country = attendance.calendar_id.company_id.country_id or self.env.company.country_id
            if not country or not self.env['hr.work.entry.type'].search_count([('country_id', '=', country.id)], limit=1):
                domain = [('country_id', '=', False)]
            else:
                domain = [('country_id', '=', country.id)]
            attendance.allowed_work_entry_type_ids = self.env['hr.work.entry.type'].search(domain)

    def _copy_attendance_vals(self):
        res = super()._copy_attendance_vals()
        res['work_entry_type_id'] = self.work_entry_type_id.id
        return res

    def _is_work_period(self):
        return self.work_entry_type_id.count_as == 'working_time' and super()._is_work_period()
