# Copyright (C) 2020: Criptomart (https://criptomart.net)
# @author Santi Noreña (<santi@criptomart.net>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from odoo import api, fields, models


class ProductTemplate(models.Model):
    _inherit = "product.template"

    margin_state = fields.Selection(store=True, compute_sudo=False)

    last_purchase_price_received = fields.Float(
        string="Last purchase price",
        help="The last price at which the product was purchased. "
        "It is used as the base price field for calculating the product sale price.",
        # readonly=True,
        digits="Product Price",
    )

    last_purchase_price_received_compute_type = fields.Selection(
        [
            ("without_discounts", "Without discounts"),
            ("with_discount", "First discount"),
            ("with_two_discounts", "Double discount"),
            ("with_three_discounts", "Triple discount"),
            ("manual_update", "Manual update"),
        ],
        string="Last purchase price calculation type",
        help="""
        Choose whether discounts should influence the calculation of the last purchase price.
        Select Never update for manual configuration of cost and sale prices.\n
        * Without discounts: does not take into account discounts when updating
          the last purchase price.\n
        * First discount: take into account only first discount when updating
          the last purchase price.\n
        * Double discount: take into account two first discounts when updating
          the last purchase price.\n
        * Triple discount: take into account all discounts when updating
          the last purchase price.
          Needs "Purchase Triple Discount" OCA module.\n
        * Manual update: Select this for manual configuration of cost and sale price.
          The sales price will not be calculated automatically.
        """,
        default="without_discounts",
        required=True,
    )

    @api.onchange(
        "last_purchase_price_received",
        "standard_price",
        "taxes_id",
        "margin_classification_id",
        "list_price",
    )
    def _onchange_standard_price(self):
        if self.last_purchase_price_received != 0:
            (
                self.margin_state,
                self.theoretical_price,
                self.theoretical_difference,
            ) = self.env["product.product"]._get_margin_info(
                self.margin_classification_id,
                self.taxes_id,
                self.name,
                self.last_purchase_price_received,
                self.list_price,
            )
