from decimal import Decimal
from trytond.model import ModelView, fields
from trytond.wizard import Wizard, StateView, StateTransition, StateAction, Button
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction
import logging
import json
from collections import defaultdict
from trytond.exceptions import UserWarning, UserError

logger = logging.getLogger(__name__)

__all__ = ['CreatePrepaymentStart', 'CreatePrepaymentWizard']
__metaclass__ = PoolMeta


class CreatePrepaymentStart(ModelView):
    'Create Prepayment Start'
    __name__ = 'purchase.create_prepayment.start'
    purchase_amount = fields.Numeric(
        'Purchase amount',
        digits=(16, 2),
        readonly=True,
        help="Purchase amount"
    )
    percentage = fields.Numeric(
        'Percentage',
        digits=(16, 2),
        readonly=False,
        help="Percentage of the purchase amount to prepay."
    )
    amount = fields.Numeric(
        'Amount',
        digits=(16, 2),
        required=True,
        help="Prepayment amount, calculated but editable."
    )

    @fields.depends('percentage','purchase_amount')
    def on_change_with_amount(self):
        if self.percentage and self.percentage > 0:
            return round(self.purchase_amount * self.percentage / 100,2)

class PrepaymentMessage(ModelView):
    'Prepayment Created Message'
    __name__ = 'purchase.create_prepayment.message'

    message = fields.Char('Message', readonly=True)
    invoice = fields.Many2One('account.invoice', 'Invoice')

class CreatePrepaymentWizard(Wizard):
    'Create Prepayment Wizard'
    __name__ = 'purchase.create_prepayment'

    start = StateView(
        'purchase.create_prepayment.start',
        'purchase_trade.create_prepayment_start_form',
        [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Create', 'create_invoice', 'tryton-ok', default=True),
        ]
    )
    create_invoice = StateTransition()
    invoice_id = None
    message = StateView(
        'purchase.create_prepayment.message',
        'purchase_trade.create_prepayment_message_form',
        [
            Button('OK', 'end', 'tryton-ok'),
            Button('See Prepayment', 'see_invoice', 'tryton-go-next'),
        ]
    )
    see_invoice = StateAction('account_invoice.act_invoice_form')

    def default_start(self, fields):
        Purchase = Pool().get('purchase.purchase')
        context = Transaction().context
        ids = context.get('active_ids')
        percentage = Decimal(0)
        amount = Decimal(0)
        purchase_amount = Decimal(0)
        for i in ids:
            purchase = Purchase(i)
            pt = purchase.payment_term.name
            if 'ADV' in pt:
                before = pt.split("ADV")[0].strip()
                percentage = Decimal(int(before.split("%")[0].strip()))            
            if purchase.lines:
                line = purchase.lines[0]
                purchase_amount = line.amount
                amount = purchase_amount * percentage / Decimal(100)
        
        return {
            'percentage': percentage,
            'purchase_amount': purchase_amount,
            'amount': amount,
            }

    def transition_create_invoice(self):
        pool = Pool()
        Invoice = pool.get('account.invoice')
        InvoiceLine = pool.get('account.invoice.line')
        Product = pool.get('product.product')
        Purchase = pool.get('purchase.purchase')

        purchase = Purchase(Transaction().context['active_id'])
        amount = self.start.amount

        # Trouver le produit "Prepayment"
        prepayment_product = Product.search([('code', '=', 'Prepayment')])

        if prepayment_product:
            prepayment_product = prepayment_product[0]
            invoice = Invoice(
                company=purchase.company,
                type='in',
                party=purchase.party,
                invoice_address=purchase.invoice_address,
                currency=purchase.currency,
                account=purchase.party.account_payable_used,
                payment_term=purchase.payment_term,
                description="Prepayment"
            )
            invoice_line = InvoiceLine(
                product=prepayment_product,
                description='Prepayment for %s' % purchase.rec_name,
                quantity=1,
                unit=prepayment_product.default_uom,
                unit_price=amount,
                account=prepayment_product.account_stock_used,
                origin=purchase.lines[0] if purchase.lines else purchase
            )
            invoice.lines = [invoice_line]
            invoice.set_journal()
            invoice.save()
            self.message.invoice = invoice  
        return 'message'
    
    def default_message(self, fields):
        return {
            'message': 'The prepayment invoice has been successfully created.',
        }

    def do_see_invoice(self, action):
        action['views'].reverse()  # pour ouvrir en form directement
        logger.info("*************SEE_INVOICE******************:%s",self.message.invoice)
        return action, {'res_id':self.message.invoice.id}
