# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import UserError

class AccountPaymentRegister(models.TransientModel):
    
    _inherit = "account.payment.register"
    
    amount = fields.Monetary(string="Amount Due Today", currency_field='currency_id', store=True, readonly=False,
                             compute='_compute_amount')

    @api.model
    def default_get(self, fields_list):
        res = super(AccountPaymentRegister, self).default_get(fields_list)
        if 'line_ids' in res:
            # Retrieve moves to pay from the context.
            if self._context.get('active_model') == 'account.move':
                lines = self.env['account.move'].browse(self._context.get('active_ids', [])).line_ids
            elif self._context.get('active_model') == 'account.move.line':
                lines = self.env['account.move.line'].browse(self._context.get('active_ids', []))
            else:
                raise UserError(_(
                    "The register payment wizard should only be called on account.move or account.move.line records."
                ))
            # Keep lines having a residual amount to pay.
            available_lines = self.env['account.move.line']
            for line in lines:
                if line.move_id.state != 'posted':
                    raise UserError(_("You can only register payment for posted journal entries."))

                if line.account_internal_type not in ('receivable', 'payable'):
                    continue
                if line.currency_id:
                    if line.currency_id.is_zero(line.amount_residual_currency):
                        continue
                else:
                    if line.company_currency_id.is_zero(line.amount_residual):
                        continue
                available_lines |= line
            move_id_list = []
            for move_line in available_lines:
                move_id_list.append(move_line.move_id.id)
            move_ids = self.env['account.move'].search([('id','in',move_id_list)])
            total_amount = 0.0
            for mv in move_ids:
                if mv.invoice_payment_term_id:
                    total_amount += mv.due_today
                else:
                    total_amount += mv.amount_total
            res['amount'] = total_amount
        return res