# -*- coding: utf-8 -*-
###############################################################################
#
#    Tech-Receptives Solutions Pvt. Ltd.
#    Copyright (C) 2009-TODAY Tech-Receptives(<http://www.techreceptives.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

from odoo.osv import expression
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, _

import odoo.addons.decimal_precision as dp

class AccountPayment(models.Model):
    _inherit = "account.payment"

    @api.one
    @api.depends('invoice_ids')
    def _get_invoice_enterprise_id(self):
        if self.invoice_ids:
            self.enterprise_id = self.invoice_ids[0].enterprise_id.id

    #enterprise_id = fields.Many2one('etourism.enterprise', string='Enterprise', track_visibility='onchange', compute='_get_invoice_enterprise_id', store=True)
    enterprise_id = fields.Many2one('etourism.enterprise', string='Enterprise', track_visibility='onchange')
    amount_total_currency = fields.Char(string='Total',
        store=True, readonly=True, compute='_compute_amount_currency')

    @api.one
    @api.depends('amount')
    def _compute_amount_currency(self):
        amount_total_currency,str_amount_total_currency = 0.0,''
        if self.enterprise_id.ebusiness_id.currency_id.name == 'EUR':
            amount_total_currency = self.amount * 110.265
            str_amount_total_currency = ('{:,.2f}'.format(amount_total_currency).replace(',', ' ').replace('.', ',').replace(' ', '.'))
            str_amount_total_currency = str_amount_total_currency + ' CVE'
        elif self.enterprise_id.ebusiness_id.currency_id.name == 'CVE':
            amount_total_currency = self.amount / 110.265
            str_amount_total_currency = ('{:,.2f}'.format(amount_total_currency).replace(',', ' ').replace('.', ',').replace(' ', '.'))
            str_amount_total_currency = str_amount_total_currency + ' €'
        self.amount_total_currency = str_amount_total_currency

    @api.model
    def create(self, vals):
        """Set Enterprise ID for payments created from Invoices
        """
        context = self._context
        if not context: context = dict()
        if context.get('active_model', '') == 'account.invoice':
            invoice = self.env['account.invoice'].search([('id', '=', context['active_id'])])
            if invoice and invoice[0].enterprise_id:
                vals['enterprise_id'] = invoice[0].enterprise_id.id
        return super(AccountPayment, self).create(vals)

    @api.model
    def default_get(self, fields):
        res = super(AccountPayment, self).default_get(fields)
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                res.update({'enterprise_id': enterprise_id.id})
        return res

    @api.multi
    def post(self):
        """ Create the journal items for the payment and update the payment's state to 'posted'.
            A journal entry is created containing an item in the source liquidity account (selected journal's default_debit or default_credit)
            and another in the destination reconciliable account (see _compute_destination_account_id).
            If invoice_ids is not empty, there will be one reconciliable move line per invoice to reconcile with.
            If the payment is a transfer, a second journal entry is created in the destination journal to receive money from the transfer account.
        """
        print "POST ACCOUNT PAYMENT" 
        for rec in self:

            if rec.state != 'draft':
                raise UserError(_("Only a draft payment can be posted. Trying to post a payment in state %s.") % rec.state)

            if any(inv.state != 'open' for inv in rec.invoice_ids):
                raise ValidationError(_("The payment cannot be processed because the invoice is not open!"))

            # Use the right sequence to set the name
            rec_name = ''
            if rec.payment_type == 'transfer':
                #sequence_code = 'account.payment.transfer'
                rec_name = self.create_uid.etourism_get_next_sequence('TRANS', 'account.payment', 'name', rec.enterprise_id.id)
            else:
                if rec.partner_type == 'customer':
                    if rec.payment_type == 'inbound':
                        rec_name = self.create_uid.etourism_get_next_sequence('CUST.IN', 'account.payment', 'name', rec.enterprise_id.id)
                    if rec.payment_type == 'outbound':
                        rec_name = self.create_uid.etourism_get_next_sequence('CUST.OUT', 'account.payment', 'name', rec.enterprise_id.id)
                if rec.partner_type == 'supplier':
                    if rec.payment_type == 'inbound':
                        rec_name = self.create_uid.etourism_get_next_sequence('SUPP.IN', 'account.payment', 'name', rec.enterprise_id.id)
                    if rec.payment_type == 'outbound':
                        rec_name = self.create_uid.etourism_get_next_sequence('SUPP.OUT', 'account.payment', 'name', rec.enterprise_id.id)
            #rec.name = self.env['ir.sequence'].with_context(ir_sequence_date=rec.payment_date).next_by_code(sequence_code)
            print "REC NAME:::::::::::::::::::"
            print rec_name			
            rec.name = rec_name

            # Create the journal entry
            amount = rec.amount * (rec.payment_type in ('outbound', 'transfer') and 1 or -1)
            move = rec._create_payment_entry(amount)

            # In case of a transfer, the first journal entry created debited the source liquidity account and credited
            # the transfer account. Now we debit the transfer account and credit the destination liquidity account.
            if rec.payment_type == 'transfer':
                transfer_credit_aml = move.line_ids.filtered(lambda r: r.account_id == rec.company_id.transfer_account_id)
                transfer_debit_aml = rec._create_transfer_entry(amount)
                (transfer_credit_aml + transfer_debit_aml).reconcile()

            rec.write({'state': 'posted', 'move_name': move.name})

    @api.multi
    def get_ebusiness_contacts(self,field=''):
        email,phone,mobile = '','',''
        if self.enterprise_id:
            ebusiness_id = self.enterprise_id.ebusiness_id
            for contact in ebusiness_id.contacts_line:
                if contact.default_contact:
                    email = contact.email
                    phone = contact.phone
                    mobile = contact.mobile
            if field == 'email':
                return email
            elif field == 'phone':
                return phone
            elif field == 'mobile':
                return mobile
        else:
            return ''

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
