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

from odoo import models, fields


class ScopCotisation(models.AbstractModel):
    _name = "scop.cotisation"
    _description = "Base des cotisations"

    year = fields.Selection(
        [(year, str(year)) for year in range(
            fields.Datetime.now().year - 1, fields.Datetime.now().year + 2)],
        string='Année de cotisation',
        required=True)

    company_id = fields.Many2one(
        comodel_name='res.company',
        string='Company', change_default=True,
        required=True, readonly=True,
        default=lambda self: self.env.user.company_id)

    company_currency_id = fields.Many2one(
        comodel_name='res.currency', related='company_id.currency_id',
        string="Company Currency", readonly=True)
    payment_term_id = fields.Many2one(
        comodel_name='account.payment.term',
        string="Conditions de paiement",
        required=True
    )
    date_cotisation = fields.Date("Date de cotisation", required=True)

    def create_contribution(self, product, partner, liasse=None, amount=0):
        Invoice = self.env['account.invoice']
        InvoiceLine = self.env['account.invoice.line']
        member_invoice = Invoice.create({
            'partner_id': partner.id,
            'liasse_fiscale_id': liasse.id,
            'type': 'out_invoice',
            'year': self.year,
            'is_contribution': True,
            'journal_id': self.company_id.contribution_journal_id.id,
            'state': 'draft',
            'account_id': partner.property_account_receivable_id.id,
            'payment_term_id': self.payment_term_id.id,
            'payment_mode_id': partner.customer_payment_mode_id.id,
            'date_invoice': self.date_cotisation,
        })

        # Création de la ligne CG Scop
        InvoiceLine.create({
            'invoice_id': member_invoice.id,
            'product_id': product.id,
            'account_id': product.property_account_income_id.id,
            'invoice_line_tax_ids': [(6, 0, product.taxes_id.ids)],
            'name': product.name,
            'price_unit': amount
        })

        return member_invoice