from odoo import models, fields, api


class OpCourseExt(models.Model):
    _inherit = 'op.course'

    description = fields.Text('Description')
    max_capacity = fields.Integer('Max Capacity', default=30)

    encoach_subject_id = fields.Many2one(
        'encoach.subject', string='Taxonomy Subject', ondelete='set null', index=True,
    )
    encoach_topic_ids = fields.Many2many(
        'encoach.topic', 'op_course_encoach_topic_rel',
        'course_id', 'topic_id', string='Topics',
    )
    learning_objective_ids = fields.Many2many(
        'encoach.learning.objective', 'op_course_learning_obj_rel',
        'course_id', 'objective_id', string='Learning Objectives',
    )
    encoach_tag_ids = fields.Many2many(
        'encoach.resource.tag', 'op_course_resource_tag_rel',
        'course_id', 'tag_id', string='Tags',
    )
    difficulty_level = fields.Selection([
        ('beginner', 'Beginner'),
        ('intermediate', 'Intermediate'),
        ('advanced', 'Advanced'),
    ])
    cefr_level = fields.Selection([
        ('pre_a1', 'Pre-A1'), ('a1', 'A1'), ('a2', 'A2'),
        ('b1', 'B1'), ('b2', 'B2'), ('c1', 'C1'), ('c2', 'C2'),
    ])

    chapter_ids = fields.One2many('encoach.course.chapter', 'course_id', string='Chapters')
    chapter_count = fields.Integer(compute='_compute_chapter_count', store=True)
    objective_count = fields.Integer(compute='_compute_objective_count')
    resource_count = fields.Integer(compute='_compute_resource_count')

    @api.depends('chapter_ids')
    def _compute_chapter_count(self):
        for rec in self:
            rec.chapter_count = len(rec.chapter_ids)

    def _compute_objective_count(self):
        for rec in self:
            rec.objective_count = len(rec.learning_objective_ids)

    def _compute_resource_count(self):
        Mat = self.env['encoach.chapter.material'].sudo()
        for rec in self:
            mats = Mat.search([
                ('chapter_id.course_id', '=', rec.id),
                ('resource_id', '!=', False),
            ])
            rec.resource_count = len(mats.mapped('resource_id'))
