# -*- coding: utf-8 -*-
##############################################################################
#
#    This module uses OpenERP, Open Source Management Solution Framework.
#    Copyright (C) 2014-Today BrowseInfo (<http://www.browseinfo.in>)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _
from datetime import datetime
from dateutil.relativedelta import relativedelta
from lxml import etree


class account_invoice(models.Model):
    
    _inherit = 'account.invoice'
    
    @api.multi
    def _get_result_over(self):
        for aml in self:
            aml.result_over = aml.amount_total - aml.credit_amount_over

    @api.multi
    def _get_credit_over(self):
        for aml in self:
            aml.credit_amount_over = aml.amount_total - aml.residual

    credit_amount_over = fields.Float(compute ='_get_credit_over',   string="Credit/paid")
    result_over = fields.Float(compute ='_get_result_over',   string="Balance") #'balance' field is not the same


    
class Res_Partner(models.Model):
    _inherit = 'res.partner'
    
    
    @api.multi
    def _get_amounts_and_date_amount_over(self):
        user_id = self._uid
        company = self.env['res.users'].browse(user_id).company_id
        current_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        for partner in self:
            amount_due = amount_overdue = 0.0
            for aml in partner.balance_invoice_over_ids:
                if (aml.company_id == company):
                    date_maturity = aml.date_due or aml.date
                    amount_due += aml.result_over
                    if (date_maturity <= current_date):
                        amount_overdue += aml.result_over
            partner.payment_amount_due_amt= amount_due
            partner.payment_amount_overdue_amt =  amount_overdue
            
    
    @api.multi        
    def do_partner_mail(self):
        unknown_mails = 0
        for partner in self:
            partners_to_email = [child for child in partner.child_ids if child.type == 'invoice' and child.email]
            if not partners_to_email and partner.email:
                partners_to_email = [partner]
            if partners_to_email:
                for partner_to_email in partners_to_email:
                    mail_template_id = self.env['ir.model.data'].xmlid_to_object('bi_payment_overdue.email_template_account_followup_default_id')
                    mail_template_id.send_mail(partner_to_email.id)
                if partner not in partners_to_email:
                        self.message_post([partner.id], body=_('Overdue email sent to %s' % ', '.join(['%s <%s>' % (partner.name, partner.email) for partner in partners_to_email])))
        return unknown_mails
    
    @api.multi
    def do_button_print(self):
        print ":IIIIIIIIIIIIIIIIIIIIIIIIIIIIII",self
        return self.env['report'].get_action(self, 'account.report_overdue')
    
    
    balance_invoice_over_ids =fields.One2many('account.invoice', 'partner_id','Customer move lines',domain=[ '&', ('type', '=', 'out_invoice'), '&', ('state', 'in', ['open','paid'])]) 
    unreconciled_aml_ids = fields.One2many('account.move.line', 'partner_id','Move lines')
    payment_amount_due_amt_over=fields.Float(compute = '_get_amounts_and_date_amount_over', string="Balance Due")
    payment_amount_overdue_amt_over = fields.Float(compute='_get_amounts_and_date_amount_over',
                                                  string="Total Overdue Amount"  )
