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

from ast import literal_eval
from odoo import fields, models, api, _


class Project(models.Model):
    _inherit = 'project.project'

    @api.multi
    def _compute_invoice_count(self):
        for project in self:
            # retrieve all projects
            project.invoice_count = self.env['account.invoice'].sudo().search_count([('project_id', '=', self.id)])

    # ------------------------------------------------------
    # Fields declaration
    # ------------------------------------------------------
    invoice_ids = fields.One2many(
        'account.invoice',
        'project_id',
        string='Factures')
    invoice_count = fields.Integer(
        compute='_compute_invoice_count',
        string='Nombre de factures')

    # ------------------------------------------------------
    # SQL Constraints
    # ------------------------------------------------------

    # ------------------------------------------------------
    # Default methods
    # ------------------------------------------------------

    # ------------------------------------------------------
    # Computed fields / Search Fields
    # ------------------------------------------------------

    # ------------------------------------------------------
    # Onchange / Constraints
    # ------------------------------------------------------

    # ------------------------------------------------------
    # CRUD methods (ORM overrides)
    # ------------------------------------------------------

    # ------------------------------------------------------
    # Actions
    # ------------------------------------------------------
    @api.multi
    def action_view_project_invoices(self):
        self.ensure_one()
        action = self.env.ref('account.action_invoice_refund_out_tree').sudo().read()[0]
        action['domain'] = [('type', 'in', ['out_invoice', 'out_refund']), ('project_id', '=', self.id)]
        return action

    @api.multi
    def action_generate_invoices(self):
        for project in self:
            for benef in project.financement_ids:
                if benef.partner_id.parent_id:
                    partner = benef.partner_id.parent_id
                else:
                    partner = benef.partner_id

                if partner.type_structure_id:
                    # search the product corresponding to the company associated
                    product_id = self.env['product.product'].search([('type_product', '=', 'collectivite')])
                else:
                    # search the product corresponding to the company associated
                    product_id = self.env['product.product'].search([('type_product', '=', 'particular')])
                # If doesn't exist, create the invoice
                if not benef.invoice_id:
                    account_invoice_id = self.create_invoice(
                        product_id, partner, benef.montant)
                    benef.write({'invoice_id': account_invoice_id.id})

    def create_invoice(self, product, partner, amount):
        result = dict()
        Invoice = self.env['account.invoice']
        InvoiceLine = self.env['account.invoice.line']
        journal_id = self.env['account.journal'].search([('company_id', '=', self.env.user.company_id.id)], limit=1)
        payment_term_id = self.env.ref('adefpat_account.account_payment_term_adefpat')
        benef_invoice = Invoice.create({
            'name': partner.name,
            'project_id': self.id,
            'partner_id': partner.id,
            'type': 'out_invoice',
            'journal_id': journal_id.id,
            'state': 'draft',
            'payment_term_id': payment_term_id.id,
            'user_id': self.user_id.id
        })

        # Création de la ligne CG Scop
        benef_invoice_line = InvoiceLine.create({
            'name': product.name,
            'invoice_id': benef_invoice.id,
            'product_id': product.id,
            'account_id': product.property_account_income_id.id,
            'account_analytic_id': self.analytic_account_id.id,
            'invoice_line_tax_ids': [(6, 0, product.taxes_id.ids)],
            'name': product.name,
            'price_unit': amount
        })
        result['invoice'] = benef_invoice
        result['invoice_line'] = benef_invoice_line
        return benef_invoice

    # ------------------------------------------------------
    # Business methods
    # ------------------------------------------------------

class ProjectTask(models.Model):
    _inherit = "project.task"

    invoice_id = fields.Many2one(
        "account.invoice",
        string="Facture liée",
        domain=[("type", "=", "in_invoice")],
        ondelete="restrict",
    )
    payment_date_invoice = fields.Date("Date de paiement de la facture")
    date_account = fields.Date("Date de la facture")


class AdefpatFinancement(models.Model):
    _inherit = 'adefpat.project.financement'

    invoice_id = fields.Many2one(
        'account.invoice',
        string='Facture liée')