from odoo import api, fields, models


class AccountMoveLine(models.Model):
    _inherit = 'account.move.line'

    purchase_price = fields.Float(
        string='Cost', compute="_compute_purchase_price", digits='Product Price', store=True, readonly=False,
        help="Compute Purchase Price")

    allow_reverse_calc = fields.Boolean(compute="_compute_allow_reverse_calc")

    @api.depends('company_id', 'move_id.move_type')
    def _compute_allow_reverse_calc(self):
        for rec in self:
            if rec.company_id.invoice_reverse_calc and rec.move_id.move_type == "out_invoice":
                rec.allow_reverse_calc = True
            else:
                rec.allow_reverse_calc = False

    @api.onchange('price_total')
    def _onchange_price_total(self):
        taxes_amount = sum(self.tax_ids.mapped('amount'))
        if self.price_total and self.allow_reverse_calc:
            perc = (len(self.tax_ids) + (taxes_amount / 100))
            if perc and self.quantity:
                self.price_unit = self.price_total / perc / self.quantity

    # =========================== Compute functions =========================== #
    @api.depends('product_id', 'company_id', 'product_uom_id')
    def _compute_purchase_price(self):
        for line in self:
            if not line.product_id:
                line.purchase_price = 0.0
                continue
            line = line.with_company(line.company_id)

            # Convert the cost to the line UoM
            product_cost = line.product_id.uom_id._compute_price(
                line.product_id.standard_price,
                line.product_uom_id,
            )

            line.purchase_price = line.currency_id.round(product_cost * line.currency_rate)

    def _compute_price_unit(self):
        """
        note:: inherit this function to compute account move line price_unit
        in credit notes depending on partner pricelist
        """
        for rec in self:
            if rec.move_id.move_type == 'out_refund' and rec.move_id.partner_id \
                    and rec.move_id.partner_id.property_product_pricelist and rec.product_id:
                price = rec.move_id.partner_id.property_product_pricelist._get_products_price(
                    rec.product_id, rec.quantity or 1.0, rec.move_id.partner_id)
                return price

        return super(AccountMoveLine, self)._compute_price_unit()
