'''
Created on Apr 4, 2022

@author: Zuhair Hammadi
'''
from odoo import models, fields, api

class AppraisalQuestionSelection(models.TransientModel):    
    _name = 'appraisal.question.selection'
    _description = 'Appraisal Question Selection'

    appraisal_id = fields.Many2one('appraisal', required = True, ondelete ='cascade')
    section_id = fields.Many2one('appraisal.section', required = True, ondelete ='cascade')
    question_selection_weight = fields.Boolean(related='section_id.question_selection_weight')
    line_ids = fields.One2many('appraisal.question.selection.line', 'selection_id')    
    
    all_required = fields.Boolean(compute = '_calc_all_required')
    
    @api.depends('line_ids.required')
    def _calc_all_required(self):
        for record in self:
            record.all_required = all(record.mapped('line_ids.required'))
    
    @api.onchange('appraisal_id', 'section_id')
    def _set_line_ids(self):
        if self.line_ids:
            return
        for question in self.section_id.question_ids:
            if question.job_ids and self.appraisal_id.employee_id.job_id not in question.job_ids:
                continue
                        
            existing_line = self.appraisal_id.line_ids.filtered(lambda l : l.question_id == question)
            self.line_ids += self.line_ids.new({
                'selection_id' : self.id,
                'question_id' : question.id,
                'selected' : bool(existing_line),
                'weight' : existing_line.weight if existing_line else question.weight
                })
    
    
    def process(self):
        sequence = 0
        for line in self.line_ids:
            sequence +=1
            existing_line = self.appraisal_id.line_ids.filtered(lambda l : l.question_id == line.question_id)
            
            print(sequence, line, line.selected, existing_line)
            
            if line.selected and not existing_line:
                self.env['appraisal.line'].create({
                    'section_id' : self.section_id.id,
                    'name' : line.question_id.name,
                    'description' : line.question_id.name,
                    'weight' : line.weight,
                    'appraisal_id' : self.appraisal_id.id,
                    'sequence' : sequence,
                    'question_id' : line.question_id.id        
                    })
                
            elif line.selected and existing_line:
                if existing_line.sequence != sequence:
                    existing_line.sequence = sequence
                if existing_line.weight != line.weight:
                    existing_line.weight = line.weight                
                
            elif not line.selected and existing_line and not line.required:
                existing_line.with_context(force_delete=True).unlink()