# -*- 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 AccountInvoice(models.Model):
    _inherit = "account.invoice"

    @api.onchange('enterprise_id')
    def onchange_enterprise(self):
        #print "ON CHANGE ENTERPRISE:::::::::::::::::::::::::::::::::::"
        if not (self.enterprise_id):
            return {'value': {}}
        else:
            self.currency_id=self.enterprise_id.ebusiness_id.sudo().currency_id

    @api.one
    @api.depends('invoice_line_ids.price_subtotal', 'tax_line_ids.amount', 'currency_id', 'company_id', 'date_invoice')
    def _compute_amount(self):
        self.amount_untaxed = sum(line.price_subtotal for line in self.invoice_line_ids)
        self.amount_tax = sum(line.amount for line in self.tax_line_ids)
        self.amount_total = self.amount_untaxed + self.amount_tax
        amount_total_company_signed = self.amount_total
        amount_untaxed_signed = self.amount_untaxed
        if self.currency_id and self.company_id and self.currency_id != self.company_id.currency_id:
            currency_id = self.currency_id.with_context(date=self.date_invoice)
            amount_total_company_signed = currency_id.compute(self.amount_total, self.company_id.currency_id)
            amount_untaxed_signed = currency_id.compute(self.amount_untaxed, self.company_id.currency_id)
        sign = self.type in ['in_refund', 'out_refund'] and -1 or 1
        self.amount_total_company_signed = amount_total_company_signed * sign
        self.amount_total_signed = self.amount_total * sign
        self.amount_untaxed_signed = amount_untaxed_signed * sign

    @api.one
    @api.depends('amount_total')
    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_total * 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_total / 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 _default_currency_custom(self):
        #print "DEFAULT CURRENCY:::::::::::::::::::::::::::::::::::"
        journal = self._default_journal()
        if self.env.uid:
            #print "IF UID:::::::::::::::::::::::::::::::::::"
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                #print "IF ENTERPRISE ID:::::::::::::::::::::::::::::::::::"
                #print enterprise_id.ebusiness_id.sudo().currency_id
                return enterprise_id.ebusiness_id.sudo().currency_id
            else:
                #print "ELSE ENTERPRISE ID:::::::::::::::::::::::::::::::::::"
                return journal.currency_id or journal.company_id.currency_id

    enterprise_id = fields.Many2one('etourism.enterprise', string='Enterprise', track_visibility='onchange')
    booking_group_id = fields.Many2one('etourism.booking.group', 'Booking')
    amount_total_currency = fields.Char(string='Total',
        store=True, readonly=True, compute='_compute_amount_currency')
    #JCF - 22-05-2018
    booking_id = fields.Many2one('etourism.booking', 'Booking')

    @api.model
    def create(self, vals):
        """Set Booking group id for invoices created from Sales Order related to Eturismo Booking
        """
        context = self._context
        booking_group_id = False
        if not context: context = dict()
        if context.get('active_model', '') == 'sale.order':
            folio = self.env['etourism.enterprise.folio'].search([('order_id', '=', context['active_id'])])
            if folio and folio[0].booking_group_id:
                vals['booking_group_id'] = folio[0].booking_group_id.id
                booking_group_id = folio[0].booking_group_id.id
        if context.get('booking_group_id', False):
            vals['booking_group_id'] = context['booking_group_id'].id
            vals['enterprise_id'] = context['booking_group_id'].enterprise_id.id
            booking_group_id = context['booking_group_id'].id

        if self.user_has_groups('ecom.group_ecom_hotel') or self.user_has_groups('etourism.group_etourism_directory_tms_operator'):
            #print "IS HOTEL:::::::::::::::::::::::"
            if self.env.uid:
                enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
                #print "ENTERPRISE ID:::::::::::::::::::::::",enterprise_id.id
                vals['enterprise_id'] = enterprise_id.id
                #print "ENTERPRISE ID VALS:::::::::::::::::::::::",vals['enterprise_id']
        if 'enterprise_id' in vals:
            #print "ENTERPRISE IN VALS:::::::::::::::::::::::"
            if vals['enterprise_id']:
                enterprise_rec = self.env['etourism.enterprise'].browse(vals['enterprise_id'])
                if enterprise_rec:
                    if enterprise_rec.ebusiness_id.sudo().currency_id:
                        vals['currency_id'] = enterprise_rec.ebusiness_id.sudo().currency_id.id
                        print "CURRENCY ID:::::::::::::::::::::::::::::",vals['currency_id']
        if booking_group_id:
            #print "CREATE INVOICE IF BOOKING GROUP ID:::::::::::::::::::::::",booking_group_id
            book_obj = self.env['etourism.booking.group'].browse([booking_group_id])
            book_obj.write({'has_invoice': True})

        return super(AccountInvoice, self).create(vals)

    @api.model
    def default_get(self, fields):
        res = super(AccountInvoice, 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

class AccountInvoiceLine(models.Model):
    _inherit = "account.invoice.line"

    @api.one
    @api.depends('price_unit', 'discount', 'invoice_line_tax_ids', 'quantity',
        'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id', 'invoice_id.company_id')
    def _compute_price(self):
        currency = self.invoice_id and self.invoice_id.currency_id or None
        price = self.price_extra_bed + ((self.price_unit * (1 - (self.discount or 0.0) / 100.0)) * self.quantity)
        taxes = False
        if self.invoice_line_tax_ids:
            taxes = self.invoice_line_tax_ids.compute_all(price, currency, 1, product=self.product_id, partner=self.invoice_id.partner_id)
        self.price_subtotal = price_subtotal_signed = taxes['total_excluded'] if taxes else price
        if self.invoice_id.currency_id and self.invoice_id.company_id and self.invoice_id.currency_id != self.invoice_id.company_id.currency_id:
            price_subtotal_signed = self.invoice_id.currency_id.compute(price_subtotal_signed, self.invoice_id.company_id.currency_id)
        sign = self.invoice_id.type in ['in_refund', 'out_refund'] and -1 or 1
        self.price_subtotal_signed = price_subtotal_signed * sign

    price_extra_bed = fields.Float('Extra Beds Price', required=True, digits=dp.get_precision('Extra Bed Price'), default=0.0)


    @api.onchange('product_id')
    def _onchange_product_id(self):
        domain = {}
        if not self.invoice_id:
            return
        booking_duration = 0
        part = self.invoice_id.partner_id
        fpos = self.invoice_id.fiscal_position_id
        company = self.invoice_id.company_id
        currency = self.invoice_id.currency_id
        type = self.invoice_id.type
        if not part:
            warning = {
                    'title': _('Warning!'),
                    'message': _('You must first select a partner!'),
                }
            return {'warning': warning}

        if not self.product_id:
            if type not in ('in_invoice', 'in_refund'):
                self.price_unit = 0.0
            domain['uom_id'] = []
        else:
            if self.product_id.product_tmpl_id.tourist_tax is True:
                if self.invoice_id.booking_group_id:
                    booking_duration = self.invoice_id.booking_group_id.duration
                    if booking_duration <= 10:
                        self.quantity = booking_duration

            if part.lang:
                product = self.product_id.with_context(lang=part.lang)
            else:
                product = self.product_id

            self.name = product.partner_ref
            account = self.get_invoice_line_account(type, product, fpos, company)
            if account:
                self.account_id = account.id
            self._set_taxes()

            if type in ('in_invoice', 'in_refund'):
                if product.description_purchase:
                    self.name += '\n' + product.description_purchase
            else:
                if product.description_sale:
                    self.name += '\n' + product.description_sale

            if not self.uom_id or product.uom_id.category_id.id != self.uom_id.category_id.id:
                self.uom_id = product.uom_id.id
            domain['uom_id'] = [('category_id', '=', product.uom_id.category_id.id)]

            if company and currency:
                if company.currency_id != currency:
                    self.price_unit = self.price_unit * currency.with_context(dict(self._context or {}, date=self.invoice_id.date_invoice)).rate

                if self.uom_id and self.uom_id.id != product.uom_id.id:
                    self.price_unit = product.uom_id._compute_price(self.price_unit, self.uom_id)
        return {'domain': domain}

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