# -*- coding: utf-8 -*-

from odoo import models, fields, api


class SOS_Zero_Location(models.Model):
    _name = 'sos_zero_location'
    _description = 'Retail Components'
    _rec_name = 'part_no'
    
    
    part_no = fields.Many2one('sos_material', string='Part No', required=True)
    material_name = fields.Char(related='part_no.name',string="Name")
    permanent_no = fields.Char(related='part_no.part_no',string="Material Code")
    inhand_quantity = fields.Float(string="In-Hand Qty")

    
    @api.model
    def create(self, vals):
        record = super(SOS_Zero_Location, self).create(vals)
        if record.part_no:
            component = record.part_no
            component.write({'inhand_stock_qty': component.inhand_stock_qty + record.inhand_quantity})
        return record
    
    def write(self, vals):
        # Capture old inhand_quantity before it gets overwritten
        old_quantity = self.inhand_quantity
        result = super(SOS_Zero_Location, self).write(vals)
        
        # Only proceed if inhand_quantity was indeed updated and part_no is set
        if 'inhand_quantity' in vals and self.part_no:
            new_quantity = vals.get('inhand_quantity', 0.0)
            difference = new_quantity - old_quantity
            # Update the associated component's inhand_qty with the difference
            if self.part_no:
                self.part_no.write({'inhand_stock_qty': self.part_no.inhand_stock_qty + difference})

        return result