from odoo import models, fields, api

class SOSCalculateMSPWizard(models.TransientModel):
    _name = 'sos_msp_wizard'
    _description = 'Calculate MSP Wizard'

    material_plan_ids = fields.Many2many('sos_material_plan_msp', string="Material Plan")
    sfg_plan_ids = fields.Many2many('sos_sfg_plan_msp', string="SFG Plan")
    currency_id = fields.Many2one('res.currency', string='Currency')
    old_msp = fields.Monetary(string="Current MSP", currency_field='currency_id')
    total_sfg_cost = fields.Monetary(
        string="Total SFG Cost",
        currency_field='currency_id',
        compute="_compute_total_cost",
        store=True
    )
    total_material_cost = fields.Monetary(
        string="Total Material Cost",
        currency_field='currency_id',
        compute="_compute_total_material_cost",
        store=True
    )
    new_msp = fields.Monetary(
        string="Maximum Selling Price",
        currency_field='currency_id',
        compute="_compute_final_cost",
        store=True
    )
    @api.depends('total_material_cost','total_sfg_cost')
    def _compute_final_cost(self):
        for record in self:
            record.new_msp = record.total_material_cost + record.total_sfg_cost
    @api.depends('material_plan_ids.final_cost')
    def _compute_total_material_cost(self):
        for record in self:
            record.total_material_cost = sum(record.material_plan_ids.mapped('final_cost'))
    
    @api.depends('sfg_plan_ids.final_cost')
    def _compute_total_cost(self):
        for record in self:
            record.total_sfg_cost = sum(record.sfg_plan_ids.mapped('final_cost'))
    @api.model
    def default_get(self, fields):
        res = super(SOSCalculateMSPWizard, self).default_get(fields)
        fg_name = self.env.context.get('fg_name')
        material_plans = self.env['sos_material_plan_msp'].search([('fg_name', '=', fg_name)])
        sfg_plans = self.env['sos_sfg_plan_msp'].search([('fg_name', '=', fg_name)])

        # Use the correct command format for Many2many fields
        res.update({
            'material_plan_ids': [(6, 0, material_plans.ids)],
            'sfg_plan_ids': [(6, 0, sfg_plans.ids)],
            'old_msp': self.env.context.get('old_msp')
            
        })
        return res
    def action_update_msp(self):
        fg_name = self.env.context.get('fg_name')
        fg_master = self.env['sos_fg'].search([('id', '=', fg_name)])
        if fg_master:
            fg_master.write({
                'msp':self.new_msp
            })
        return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'message': "Updated Successfully",
                    'type': 'success',
                    'sticky': False
                }
            }
        

