# © 2020 Le Filament (<http://www.le-filament.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from odoo import api, fields, models


class AccountBankingMandateChange(models.TransientModel):
    _name = "account.banking.mandate.change.wizard"
    _description = "Wizard changement mandat"

    @api.model
    def _default_mandate_id(self):
        return self.env.context.get("active_id")

    @api.model
    def _default_invoice_ids(self):
        invoice_ids = (
            self.env["account.banking.mandate"]
            .browse(self.env.context.get("active_id"))
            ._select_open_invoices()
        )
        return invoice_ids

    mandate_id = fields.Many2one(
        comodel_name="account.banking.mandate",
        string="Mandat",
        default=_default_mandate_id,
        required=True,
    )
    partner_id = fields.Many2one(related="mandate_id.partner_id")
    invoice_ids = fields.Many2many(
        comodel_name="account.move",
        string="Factures",
        default=_default_invoice_ids,
    )

    def change_mandate(self):
        if self.env.context.get("action_type") == "update_mandate":
            self.mandate_id._change_invoice_mandate(self.invoice_ids)

        elif self.env.context.get("action_type") == "remove_mandate":
            self.mandate_id._remove_invoice_mandate(self.invoice_ids)