from odoo import models, fields, api
import logging


class MrpWorkorder(models.Model):
    _inherit = 'mrp.workorder'

    product_sources_id = fields.Many2one(comodel_name='product.product', string='Main manufactured product', compute='_compute_sources_id', store=True)
    production_sources_id = fields.Many2one(comodel_name='mrp.production', string='Main manufactured production', compute='_compute_sources_id', store=True)
    bending_radius = fields.Float(string='Bending Radius', related='operation_id.bending_radius', store=True)
    sale_date = fields.Datetime(string='Date Sale Order', related='sale_order_id.date_order', store=True)
    material_ids = fields.Many2many(string='Комлектующие заявки', comodel_name='product.product', compute='_compute_material_ids', store=True)
    sale_order_id = fields.Many2one(comodel_name='sale.order', string='Связанная продажа', compute='_compute_sources_id', store=True)


    @api.depends('production_id.move_raw_ids.product_id', 'production_id.move_raw_ids', 'production_id')
    def _compute_material_ids(self):
        for rec in self:
            if rec.production_id and rec.production_id.move_raw_ids:
                records = rec.production_id.move_raw_ids.mapped('product_id')
                rec.material_ids = records
            else:
                rec.material_ids = False

    @api.depends('production_id')
    def _compute_sources_id(self):
        for rec in self:
            production = rec._get_sources_while(rec.production_id)
            rec.production_sources_id = production.id
            rec.product_sources_id = production.product_id.id
            rec.sale_order_id = rec.production_sources_id.sale_line_id.order_id if rec.production_sources_id and rec.production_sources_id.sale_line_id else False

    def _get_sources_while(self, production):
        production_new = production._get_sources()
        if production_new:
            return self._get_sources_while(production_new)
        else:
            return production