# -*- 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/>.
#
###############################################################################
import time
import datetime
from dateutil.relativedelta import relativedelta
import math

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, _
from odoo.tools.misc import formatLang
import json

import urlparse
import uuid

from datetime import date


def splitthousands(s, sep='.'):
    str_s = ''
    if s:
        str_s = str(s)	
    if len(str_s) <= 3: return str_s  
    amount = splitthousands(str_s[:-3], sep) + sep + str_s[-3:]
    return amount


class EtourismEnterpriseFolio(models.Model):

    _inherit = 'etourism.enterprise.folio'
    _order = 'booking_group_id desc'

    booking_group_id = fields.Many2one(comodel_name='etourism.booking.group',string='Booking Group Id')
    booking_id = fields.Many2one(comodel_name='etourism.booking',string='Booking Id')


class EtourismEnterpriseFolioLineExt(models.Model):

    _inherit = 'etourism.enterprise.folio.line'

    #JCF - 22-05-2018
    status = fields.Selection([('not_invoiced', 'Not Invoiced'),('invoiced', 'Invoiced')], 'Status', default='not_invoiced', track_visibility='onchange',translate=False)

    @api.multi
    def write(self, vals):
        """
        Overrides orm write method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        update Hotel Room Reservation line history"""
        print "WRITE FOLIO LINE: ", vals
        booking_line_obj = self.env['etourism.booking']
        room_obj = self.env['etourism.room']
        prod_id = vals.get('product_id') or self.product_id.id
        booking_id = vals.get('booking_id') or self.booking_id.id
        print "BOOKING ID:::::::::::::",booking_id
        chkin = vals.get('checkin_date') or self.checkin_date
        chkout = vals.get('checkout_date') or self.checkout_date
        is_reserved = self.is_reserved

        if prod_id and is_reserved:
            print "IS RESERVED:::::::::::::::::::::::: "
            prod_domain = [('product_id', '=', prod_id)]
            prod_room = room_obj.search(prod_domain, limit=1)

            if (self.product_id and self.checkin_date and self.checkout_date):
                old_prd_domain = [('product_id', '=', self.product_id.id)]
                old_prod_room = room_obj.search(old_prd_domain, limit=1)
                if prod_room and old_prod_room:
                    # check for existing room lines.
                    srch_rmline = [('room_id', '=', old_prod_room.id),
                                   ('checkin', '=', self.checkin_date),
                                   ('checkout', '=', self.checkout_date),
                                   ]
                    rm_lines = booking_line_obj.search(srch_rmline)
                    if rm_lines:
                        rm_line_vals = {'room_id': prod_room.id,
                                        'checkin': chkin,
                                        'checkout': chkout,
                                        'booking_id': booking_id}
                        rm_lines.write(rm_line_vals)
        return super(EtourismEnterpriseFolioLineExt, self).write(vals)


class EtourismBookingGroup(models.Model):
    _name = 'etourism.booking.group'
    _inherit = 'mail.thread'
    _description = "Booking Group"
    _rec_name = "reservation_no"
    _order = "booking_date desc"

    #JCF - 13-04-2017
    @api.one
    @api.depends('booking_line')
    def _get_total_amount(self):
        if not self.booking_line:
            return {}
        res = {}
        for booking_group in self:
            if booking_group.booking_line:
                res[booking_group.id] = reduce(lambda x, y: x + y.amount, booking_group.booking_line, 0.0)
            else:
                res[booking_group.id] = 0.0
        self.total_amount=res[booking_group.id]

    #JCF - 26-05-2017
    @api.one
    @api.depends('folio_line')
    def _get_folio(self):
        if self.folio_line:
            for folio in self.folio_line:
                if folio.state=='sale' or folio.state=='sent' or folio.state=='done':
                    self.has_order=True
                    self.has_folio=True
                elif folio.state=='draft':
                    self.has_order=False
                    self.has_folio=True
                else:
                    self.has_order=False
                    self.has_folio=False
        else:
            self.has_order=False
            self.has_folio=False
        if self.invoice_line:
            self.has_invoice=True
        else:
            self.has_invoice=False

    @api.multi
    @api.depends('booking_line')
    def _get_booking_data(self):
        for booking in self:
            guests,emails = [],[]
            num_adults, num_children, num_rooms, duration = 0, 0, 0, 0

            for line in booking.booking_line:
                num_adults += line.num_adults
                num_children += line.num_children
                num_rooms += line.room_id and 1 or 0
                for guest in line.guest_ids:
                    if guest.name:
                        guests.append(guest.name)
                    if guest.email:
                        emails.append(guest.email)
            result = ' | '.join(guests)
            result2 = ' | '.join(emails)
            booking.guest_names = result
            booking.guest_emails = result2

            booking.num_adults = num_adults
            booking.num_children = num_children
            booking.num_rooms = num_rooms
            # calculate duration
            checkout_date_dur = booking.checkout
            if checkout_date_dur:
                checkout_date_dur = checkout_date_dur.split(' ')[0] + str(' 15:00:00')
            duration = self.onchange_check_dates(booking.checkin, checkout_date_dur)
            duration = duration.get('duration', 0)
            booking.duration = duration

    @api.multi
    @api.depends('contract_percentage','total_amount')
    def _get_prime_commission(self):
        for booking in self:
            contract_percentage,total_amount,prime_commission = 0.0,0.0,0.0
            contract_percentage=(booking.contract_percentage * 1.0) / (100 * 1.0)
            total_amount=booking.total_amount
            if contract_percentage and total_amount:            
                prime_commission = contract_percentage * total_amount
            booking.prime_commission = prime_commission

    @api.one
    @api.depends('noshow_token')
    def _compute_noshow_url(self):
        base_url = self.env['ir.config_parameter'].get_param('web.base.url')
        for booking in self:
            url = '%s' % urlparse.urljoin(base_url, 'noshow/%s/%s'%(booking.id, booking.noshow_token))
            booking.noshow_url = url

    @api.model
    def _default_source_id(self):
        return self.env['etourism.source'].search([('code','=','SRCP001')], limit=1)

    @api.multi
    @api.depends('booking_line')
    def _pricelist_currency(self):
        currency_symbol = ''
        for booking in self:
            for line in booking.booking_line:
                currency_symbol = line.pricelist_item_id.pricelist_id.currency_id.symbol
            booking.currency_symbol = currency_symbol

    @api.one
    @api.depends('checkin')
    def _get_checkin_date_format(self):
        for booking in self:
            booking.date_checkin  = datetime.datetime.strptime(booking.checkin, '%Y-%m-%d %H:%M:%S').date()

    @api.one
    @api.depends('checkout')
    def _get_checkout_date_format(self):
        for booking in self:
            booking.date_checkout  = datetime.datetime.strptime(booking.checkout, '%Y-%m-%d %H:%M:%S').date()

    @api.one
    @api.depends('booking_date')
    def _get_booking_date_format(self):
        for booking in self:
            booking.date_booking  = datetime.datetime.strptime(booking.booking_date, '%Y-%m-%d %H:%M:%S').date()

    @api.one
    @api.depends('num_adults','num_children')
    def _get_num_guests(self):
        num_adults,num_children = 0,0
        for booking in self:
            num_adults  = booking.num_adults
            num_children  = booking.num_children
            booking.num_guests = num_adults + num_children

    @api.one
    @api.depends('total_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.total_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.total_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

    #name = fields.Char(string='Name')
    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise')
    reservation_no = fields.Char('Reservation No', size=64, readonly=True)
    receipt_number = fields.Char(string='Receipt Number')
    payment_reference = fields.Char(string='Payment Reference')
    booking_date = fields.Datetime('Booking Date', required=True, readonly=True,
                                 default=(lambda *a:
                                          time.strftime
                                          (DEFAULT_SERVER_DATETIME_FORMAT)))
    checkin = fields.Datetime(string='Checkin')
    checkout = fields.Datetime(string='Checkout')
    duration = fields.Integer(string='Duration', compute='_get_booking_data', store=True, multi=True)
    state = fields.Selection([('request','New'),('pending', 'Pending'),
                              ('confirmed', 'Confirmed'),
                              ('no_show', 'No Show'),
                              ('cancelled', 'Cancelled'),
                              ('hosted', 'Checkin'),
                              ('checkout', 'Checkout')
                              ], 'State', default='request', track_visibility='onchange',translate=False)
    num_rooms = fields.Integer(string='Number of rooms', compute='_get_booking_data', store=True, multi=True)
    num_adults = fields.Integer(string='Number of adults', compute='_get_booking_data', store=True, multi=True)
    num_children = fields.Integer(string='Number of children', compute='_get_booking_data', store=True, multi=True)
    num_extra_bed = fields.Integer(string='Number of extra beds')
    room_type = fields.Char(string='Type of room')
    total_amount = fields.Float(string='Total Amount', compute='_get_total_amount', store=True)
    #Client tab
    client_name = fields.Char(string='Client name')
    client_country = fields.Char(string='Country')
    client_nationality = fields.Char(string='Nationality')
    client_email = fields.Char(string='Email')
    client_phone = fields.Char(string='Phone')
    client_address = fields.Char(string='Address')
    client_id_number = fields.Char(string='ID Number')
    client_motive = fields.Char(string='Motive')

    description = fields.Text(string='Description')
    enterprise = fields.Char(string='Enterprise Name Import')
    booking_id = fields.Integer(string='Booking ID')
    booking_line = fields.One2many('etourism.booking', 'booking_group_id', string="Booking(s)")
    guest_id= fields.Many2one('res.partner', 'Client Name',required=True, readonly=True,
                                 states={'confirmed': [('readonly', False)],'request': [('readonly', False)]}, track_visibility='onchange')
    #folio_id = fields.Many2many('etourism.enterprise.folio', 'enterprise_folio_booking_rel','order_id', 'invoice_id', string='Folio')
    has_default_enterprise = fields.Boolean('Has Default Enterprise', help="True, if User creating Booking group has related Enterprise.")
    origin = fields.Selection([('site', 'Site'),
                              ('pms', 'PMS'),('tourism', 'Tourism CV'),('agency', 'Agency Site')], 'Channel', default='pms', track_visibility='onchange',translate=False)
    folio_line = fields.One2many('etourism.enterprise.folio', 'booking_group_id', string="Folio(s)")
    has_folio = fields.Boolean(string='Has folio',default=False, compute='_get_folio', store=True)
    has_order = fields.Boolean(string='Has order',default=False, compute='_get_folio', store=True)
    #booking_request = fields.Boolean(string='Booking request',default=True)
    guest_names = fields.Char(compute="_get_booking_data", string="Guests", store=True)
    invoice_line = fields.One2many('account.invoice', 'booking_group_id', string="Invoice(s)")
    has_invoice = fields.Boolean(string='Has invoices',default=False, compute='_get_folio', store=True)
    motive = fields.Selection([('recreation', 'Recreation'),('business', 'Business'),
                              ('others', 'Others')
                              ], 'Motive', track_visibility='onchange',translate=False)
    guest_name = fields.Char(string='Guest Name', related='guest_id.name', readonly=True)
    ebusiness_id = fields.Many2one('ecom.ebusiness', related="enterprise_id.ebusiness_id", string='Ebusiness', store=True)
    contract_percentage = fields.Integer(string='Commission Percentage')
    prime_commission = fields.Float(string='Commission', compute='_get_prime_commission', store=True)
    #JCF - 16-08-2017
    island_id = fields.Many2one('ecom.location', related="enterprise_id.island_id", string='Island', store=True)
    county_id = fields.Many2one('ecom.location', related="enterprise_id.county_id", string='County', store=True)
    #JCF - 18-08-2017
    tms_version = fields.Selection([('v1', 'V 01'),
                              ('v2', 'V 02'),('v3', 'V 03')], 'TMS Version', default='v3', track_visibility='onchange',translate=False)
    #planning_request = fields.Boolean(string='Booking request', default=True)
    #JCF - 29-12-2017
    noshow_token = fields.Char('No-Show Token', copy=False, default=lambda self: str(uuid.uuid4()), required=True)
    noshow_url = fields.Char(compute="_compute_noshow_url", string="No-Show URL", store=True)
    noshow_date = fields.Datetime(string='No-Show Date')
    noshow_state = fields.Selection([('answered', 'Answered'),('unanswered', 'Unanswered')], 'Survey State', default='unanswered',translate=False)
    noshow_obs = fields.Text(string='Observations')
    noshow_reason_id = fields.Many2one('etourism.noshow.reason', 'Reason')
    #JCF - 02-02-2018
    guest_email = fields.Char(string='Client Email',track_visibility='onchange')
    #JCF - 02-03-2018
    source_id = fields.Many2one('etourism.source', 'Source', default=_default_source_id)
    #JCF - 04-04-2018
    currency_symbol = fields.Char(string='Currency Symbol', compute='_pricelist_currency', store=True)
    #JCF - 11-04-2018
    guest_emails = fields.Char(compute="_get_booking_data", string="Guest Emails", store=True)
    date_checkin = fields.Date(string='Date Checkin', compute='_get_checkin_date_format', store=True)
    date_checkout = fields.Date(string='Date Checkout', compute='_get_checkout_date_format', store=True)
    guest_country = fields.Many2one('res.country', string="Client's country")
    #JCF - 27-04-2018
    num_guests = fields.Integer(string='Number of guests', compute='_get_num_guests', store=True)
    date_booking = fields.Date(string='Date Booking', compute='_get_booking_date_format', store=True)
    #JCF - 04-06-2018
    amount_total_currency = fields.Char(string='Total',readonly=True, compute='_compute_amount_currency')
    #JCF - 04-03-2019
    agency_id = fields.Many2one('etourism.enterprise', 'Agency')
    #JCF - 04-03-2019
    cancellation_reason_id = fields.Many2one('etourism.booking.cancellation.reason', 'Reason for cancellation')
    day_use = fields.Boolean(string='Day Use',default=False)
    client_language = fields.Selection([('pt','Portuguese'),('en', 'English'),('fr', 'French')], 'Client Language (Notifications)', required=True)

    @api.onchange('booking_line')
    def onchange_booking_line(self):
        print "################ BOOKING LINE CHANGE ###################"
        if self.booking_line:
            for booking in self:

                guests = []
                num_adults, num_children, num_rooms, duration = 0, 0, 0, 0
                chekin_list, checkout_list = [], []

                for line in booking.booking_line:
                    num_adults += line.num_adults
                    num_children += line.num_children
                    num_rooms += line.room_id and 1 or 0
                    chekin_list.append(line.checkin)
                    checkout_list.append(line.checkout)
                    print "LINE CHECKIN:::::::::::::::::::::",line.checkin
                    print "LINE CHECKOUT:::::::::::::::::::::",line.checkout
                    for guest in line.guest_ids:
                        guests.append(guest.name)
                result = ' | '.join(guests)
                booking.guest_names = result
                booking.checkin = min(chekin_list)
                booking.checkout = max(checkout_list)
                booking.num_adults = num_adults
                booking.num_children = num_children
                booking.num_rooms = num_rooms
                # calculate duration
                checkout_date_dur = self.checkout
                checkout_date_dur = checkout_date_dur.split(' ')[0] + str(' 15:00:00')
                duration = self.onchange_check_dates(self.checkin, checkout_date_dur)
                duration = duration.get('duration', 0)
                booking.duration = duration

            self._get_total_amount()

    @api.model
    def default_get(self, fields):
        res = super(EtourismBookingGroup, 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, 'has_default_enterprise': True})
        return res

    @api.model
    def fields_get(self, fields=None, attributes=None):
        """ Hide fields from advanced search
        """
        fields_to_hide = ['booking_date','checkin','checkout','currency_symbol','noshow_token','noshow_url','noshow_date','noshow_obs']
        fields = super(EtourismBookingGroup, self).fields_get(fields, attributes=attributes)
        for field in fields_to_hide:
            if field in fields:
                fields[field]['selectable'] = False
        return fields

    @api.multi
    def onchange_check_dates(self, checkin_date=False, checkout_date=False,
                             duration=False):
        '''
        This method gives the duration between check in checkout if
        customer will leave only for some hour it would be considers
        as a whole day. If customer will checkin checkout for more or equal
        hours, which configured in company as additional hours than it would
        be consider as full days
        --------------------------------------------------------------------
        @param self: object pointer
        @return: Duration and checkout_date
        '''
        value = {}
        duration = 0
        if checkin_date and checkout_date:
            chkin_dt = (datetime.datetime.strptime
                        (checkin_date, DEFAULT_SERVER_DATETIME_FORMAT))
            chkout_dt = (datetime.datetime.strptime
                         (checkout_date, DEFAULT_SERVER_DATETIME_FORMAT))
            dur = chkout_dt - chkin_dt
            duration = dur.days
        value.update({'duration': duration})
        return value

    @api.multi
    def action_pending(self):
        count=0
        for booking in self:
            room_ids = []
            for line_id in booking.booking_line:
                checkin_dt = (datetime.datetime.strptime(line_id.checkin, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00,second=00) + datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')
                checkout_dt = (datetime.datetime.strptime(line_id.checkout, '%Y-%m-%d %H:%M:%S').replace(hour=13, minute=00,second=00) - datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

                self._cr.execute("select count(*) from etourism_booking  "
                         "where (checkin,checkout) overlaps \
                         ( timestamp %s, timestamp %s ) "
                         "and room_id = %s "
                         "and state in ('request','confirmed','pending','checkout','hosted') "
                         "and id <> %s ",
                         (checkin_dt, checkout_dt,
                          line_id.room_id.id, line_id.id))
                res = self._cr.fetchone()
                if res:
                    count = count + res[0]
                    room_ids.append(line_id.room_id.id)
            if count > 0:
                raise ValidationError(_('You tried to create reservation with rooms that already have been reserved in this reservation period. Room ID\'s: %s'%(room_ids)))
            else:
                self.write({'state': 'pending'})
                for line_id in booking.booking_line:
                    line_id.write({'state': 'pending'})
        return True

    @api.multi
    def action_confirmed(self):
        count=0
        for booking in self:
            room_ids = []
            if not booking.booking_line:
                raise ValidationError(_('You tried to confirm reservation without selecting rooms'))
            else:
                for line_id in booking.booking_line:
                    checkin_dt = (datetime.datetime.strptime(line_id.checkin, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00,second=00) + datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')
                    checkout_dt = (datetime.datetime.strptime(line_id.checkout, '%Y-%m-%d %H:%M:%S').replace(hour=13, minute=00,second=00) - datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

                    self._cr.execute("select count(*) from etourism_booking  "
                             "where (checkin,checkout) overlaps \
                             ( timestamp %s, timestamp %s ) "
                             "and room_id = %s "
                             "and state in ('request','confirmed','pending','checkout','hosted') "
                             "and id <> %s ",
                             (checkin_dt,
                              checkout_dt,
                              line_id.room_id.id, line_id.id))
                    res = self._cr.fetchone()
                    if res:
                        count = count + res[0]
                        room_ids.append(line_id.room_id.id)
                if count > 0:
                    raise ValidationError(_('You tried to confirm reservation with rooms that already have been reserved in this reservation period. Room ID\'s: %s'%(room_ids)))
                else:
                    pass
                    self.write({'state': 'confirmed'})
                    for line_id in booking.booking_line:
                        line_id.write({'state': 'confirmed'})
        return True

    @api.multi
    def action_confirm_via_planning(self):
        count=0
        for booking in self:
            room_ids = []
            for line_id in booking.booking_line:
                checkin_dt = (datetime.datetime.strptime(line_id.checkin, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00,second=00) + datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')
                checkout_dt = (datetime.datetime.strptime(line_id.checkout, '%Y-%m-%d %H:%M:%S').replace(hour=13, minute=00,second=00) - datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

                self._cr.execute("select count(*) from etourism_booking  "
                         "where (checkin,checkout) overlaps \
                         ( timestamp %s, timestamp %s ) "
                         "and room_id = %s "
                         "and state in ('request','confirmed','pending','checkout','hosted') "
                         "and id <> %s ",
                         (checkin_dt, checkout_dt,
                          line_id.room_id.id, line_id.id))
                res = self._cr.fetchone()
                if res:
                    count = count + res[0]
                    room_ids.append(line_id.room_id.id)
            if count > 0:
                raise ValidationError(_('You tried to create reservation with rooms that already have been reserved in this reservation period. Room ID\'s: %s'%(room_ids)))
            else:
                self.write({'state': 'confirmed'})
                for line_id in booking.booking_line:
                    line_id.write({'state': 'confirmed'})
        return True

    @api.multi
    def action_create_folio(self):
        """
        This method is for create new enterprise folio.
        -----------------------------------------
        @param self: The object pointer
        @return: new record set for enterprise folio.
        """
        print "CREATE FOLIO::::::::::::::: ",
        if self.has_order is True:
            raise ValidationError(_('This booking already has a quotation created.'))
        else:
            if self.user_has_groups('ecom.group_ecom_hotel_own_pms'):
                pass
            else:
                enterprise_folio_obj = self.env['etourism.enterprise.folio']
                sale_order_obj = self.env['sale.order']
                room_obj = self.env['etourism.room']
                for booking in self:
                    folio_lines = []
                    checkin_date = booking['checkin']
                    checkout_date = booking['checkout']
                    if not self.checkin < self.checkout:
                        raise ValidationError(_('Checkout date should be greater than the Checkin date'))
                    checkout_date_dur = self.checkout
                    checkout_date_dur = checkout_date_dur.split(' ')[0] + str(' 15:00:00')
                    duration_vals = (self.onchange_check_dates
                             (checkin_date=checkin_date,
                              checkout_date=checkout_date_dur, duration=False))
                    duration = duration_vals.get('duration') or 0.0

                    booking_pricelist_id = False

                    folio_vals = {
						'date_order': booking.booking_date,
						'enterprise_id': booking.enterprise_id.id,
						'partner_id': booking.guest_id.id,
						'partner_invoice_id': booking.guest_id.id,
						'partner_shipping_id': booking.guest_id.id,
						'checkin_date': booking.checkin,
						'checkout_date': booking.checkout,
						'duration': duration,
						'booking_group_id': booking.id,
						'amount_untaxed': booking.total_amount,
						'amount_total': booking.total_amount,
                    }

                    date_a = (datetime.datetime
                     (*time.strptime(booking['checkout'],
                                      DEFAULT_SERVER_DATETIME_FORMAT)[:5]))
                    date_b = (datetime.datetime
                      (*time.strptime(booking['checkin'],
                                      DEFAULT_SERVER_DATETIME_FORMAT)[:5]))
                    for line in booking.booking_line:
                        if line.pricelist_item_id and line.pricelist_item_id.pricelist_id and not booking_pricelist_id:
                            booking_pricelist_id = line.pricelist_item_id.pricelist_id.id
                        booking_line_name = line.room_id.product_id and line.room_id.product_id.name or ''
                        booking_line_name += line.booking_condition_id and line.booking_condition_id.name or ''
                        folio_lines.append((0, 0, {
						'checkin_date': checkin_date,
						'checkout_date': checkout_date,
						'product_id': line.room_id.product_id and line.room_id.product_id.id,
						'name': booking_line_name or '/',
						'product_uom_qty': ((date_a - date_b).days),
						'price_unit': line.unitary_amount,
						'price_extra_bed': line.extra_beds_amount,
						'price_reduce': line.unitary_amount,
						'price_subtotal': line.amount,
						'booking_line_id': line.id,
						'is_reserved': True}))

                    folio_vals.update({'room_lines': folio_lines, 'pricelist_id': booking_pricelist_id})
                    folio = enterprise_folio_obj.create(folio_vals)
                    self._cr.execute('insert into enterprise_folio_booking_rel'
                             '(order_id, invoice_id) values (%s,%s)',
                             (booking.id, folio.id))
                    sale_order = sale_order_obj.search([('id','=',folio.order_id.id)])

                    sale_order.write({'booking_group_id': booking.id})
                    booking.write({'has_folio': True})

        return self.env['warning'].info(title=_('Success!'), message=_('The folio was created successfully!!'))

    @api.multi
    def action_create_invoice(self):
        for booking_group in self:
            folio_id = False
            if self.folio_line:
                ctx = dict(
						default_booking_group_id=self.id,
                )

                return {
					'name': _('Folio lines'),
					'view_type': 'form',
					'view_mode': 'form',
					'res_model': 'etourism.booking.group.invoice.wizard',
					'view_id': False,
					'type': 'ir.actions.act_window',
					'target': 'new',
                    'context': ctx,
                }

                return self.env['warning'].info(title=_('Success!'), message=_('The invoice was created successfully!!'))
            else:
                return self.env['warning'].info(title=_('Warning!'), message=_('This booking group has no folio created yet!!'))


    @api.multi
    def action_confirm_folio(self):
        if self.user_has_groups('ecom.group_ecom_hotel_own_pms'):
            pass
        else:
            if self.folio_line:
                for folio in self.folio_line:
                    if folio.state=='sale':
                        raise ValidationError(_('This booking already has a sale order created.'))
                    else:
                        for order in folio.order_id:
                            order.state = 'sale'
                            order.order_line._action_procurement_create()
                            if not order.project_id:
                                for line in order.order_line:
                                    if line.product_id.invoice_policy == 'cost':
                                        order._create_analytic_account()
                                        break
                        if self.env['ir.values'].get_default('sale.config.settings','auto_done_setting'):
                            self.order_id.action_done()
                        self.write({'has_order': True})
                return self.env['warning'].info(title=_('Success!'), message=_('The sale order was created successfully!!'))

    @api.multi
    def action_cancelled(self):
        print "CANCELLED:::::::::::::::::::::::"
        if self.booking_line:
            # print "LEN BOOKING LINE::::::::::::::: ",len(self.booking_line)
            #if len(self.booking_line) > 1:
            # print "WILL CALL THE WIZARD:::::::::::::::"
            ctx = dict(
                default_booking_group_id=self.id,
                default_num_bookings = len(self.booking_line)
            )

            return {
                    'name': _('Booking lines'),
                    'view_type': 'form',
                    'view_mode': 'form',
                    'res_model': 'etourism.booking.cancel.wizard',
                    'view_id': False,
                    'type': 'ir.actions.act_window',
                    'target': 'new',
                    'context': ctx,
            }
            '''else:
                print "ONLY ONE BOOKING LINE:::::::::::::::", self.booking_line.id
                for line_id in self.booking_line:
                    line_id.action_cancelled()'''
        return True

    @api.multi
    def action_hosted(self):
        print "AQUI2:::::::::::::::::::::::"
        from_dt = datetime.date.today()
        checkin = datetime.datetime.strptime(self.checkin, '%Y-%m-%d %H:%M:%S').date()
        if from_dt < checkin:
            raise ValidationError(_('You cannot checkin before checkin date.'))
        else:
            if self.booking_line:
                #print "LEN BOOKING LINE::::::::::::::: ",len(self.booking_line)
                if len(self.booking_line) > 1:
                    #print "WILL CALL THE WIZARD:::::::::::::::"
                    ctx = dict(
						default_booking_group_id=self.id
                    )

                    return {
					'name': _('Booking lines'),
					'view_type': 'form',
					'view_mode': 'form',
					'res_model': 'etourism.booking.checkin.wizard',
					'view_id': False,
					'type': 'ir.actions.act_window',
					'target': 'new',
                    'context': ctx,
                    }
                else:
                    print "ONLY ONE BOOKING LINE:::::::::::::::", self.booking_line.id
                    self.write({'state': 'hosted'})
                    for line_id in self.booking_line:
                        line_id.action_hosted()

        return True

    @api.multi
    def action_checkout(self):
        if self.user_has_groups('ecom.group_ecom_hotel_own_pms'):
            pass
        else:
            if self.folio_line:
                for folio in self.folio_line:
                    if folio.state=='draft':
                        raise ValidationError(_('You have to create a sale order before checkout.'))

            if self.booking_line:
                #print "LEN BOOKING LINE::::::::::::::: ",len(self.booking_line)
                if len(self.booking_line) > 1:
                    #print "WILL CALL THE WIZARD:::::::::::::::"
                    ctx = dict(
						default_booking_group_id = self.id
                    )

                    return {
					'name': _('Booking lines'),
					'view_type': 'form',
					'view_mode': 'form',
					'res_model': 'etourism.booking.checkout.wizard',
					'view_id': False,
					'type': 'ir.actions.act_window',
					'target': 'new',
                    'context': ctx,
                    }
                else:
                    #print "ONLY ONE BOOKING LINE:::::::::::::::"
                    self.write({'state': 'checkout'})
                    for line_id in self.booking_line:
                        line_id.write({'state': 'checkout'})
        return True

    @api.multi
    def action_no_show(self):
        print "NO SHOW:::::::::::::::::::::::"
        from_dt = datetime.date.today()
        checkin = datetime.datetime.strptime(self.checkin, '%Y-%m-%d %H:%M:%S').date()
        if from_dt < checkin:
            raise ValidationError(_('You cannot set a No Show before checkin date.'))
        else:
            if self.booking_line:
                # print "LEN BOOKING LINE::::::::::::::: ",len(self.booking_line)
                if len(self.booking_line) > 1:
                    # print "WILL CALL THE WIZARD:::::::::::::::"
                    ctx = dict(
                        default_booking_group_id=self.id
                    )

                    return {
                        'name': _('Booking lines'),
                        'view_type': 'form',
                        'view_mode': 'form',
                        'res_model': 'etourism.booking.no_show.wizard',
                        'view_id': False,
                        'type': 'ir.actions.act_window',
                        'target': 'new',
                        'context': ctx,
                    }
                else:
                    print "ONLY ONE BOOKING LINE:::::::::::::::", self.booking_line.id
                    for line_id in self.booking_line:
                        line_id.action_no_show()
        return True

    @api.constrains('checkin', 'checkout')
    def check_in_out_dates(self):
        """
        When date_order is less then checkin date or
        Checkout date should be greater than the checkin date.
        """
        if self.checkout and self.checkin:
            checkin = datetime.datetime.strptime(self.checkin, '%Y-%m-%d %H:%M:%S').date()
            checkout = datetime.datetime.strptime(self.checkout, '%Y-%m-%d %H:%M:%S').date()
            booking_date = datetime.datetime.strptime(self.booking_date, '%Y-%m-%d %H:%M:%S').date()
            today = datetime.datetime.now().date()
            if self.checkout < self.checkin:
                raise ValidationError(_('Checkout date should be greater than Checkin date.'))

    @api.onchange('checkin')
    def onchange_checkin_date(self):
        if not (self.checkin):
            return {'value': {}}
        else:
            chkin_dt = datetime.datetime.strptime(self.checkin,'%Y-%m-%d %H:%M:%S')
            checkin_date = chkin_dt.replace(hour=15, minute=00, second=00)
            self.checkin=checkin_date
            if self.checkout:
                chkout_dt = datetime.datetime.strptime(self.checkout,'%Y-%m-%d %H:%M:%S')
                checkout_date = chkout_dt.replace(hour=13, minute=00, second=00)
                checkout_date_dur = chkout_dt.replace(hour=15, minute=00, second=00)
                if checkout_date <= checkin_date:
                    checkout_date = checkin_date + datetime.timedelta(days=1)
                dur = checkout_date_dur - checkin_date
                duration = dur.days
                self.duration=duration
                self.checkout=checkout_date

    @api.onchange('checkout')
    def onchange_checkout_date(self):
        if not (self.checkout):
            return {'value': {}}
        else:
            if self.checkin:
                chkin_dt = datetime.datetime.strptime(self.checkin,'%Y-%m-%d %H:%M:%S')
                checkin_date = chkin_dt.replace(hour=15, minute=00, second=00)
                chkout_dt = datetime.datetime.strptime(self.checkout,'%Y-%m-%d %H:%M:%S')
                checkout_date = chkout_dt.replace(hour=13, minute=00, second=00)
                if chkin_dt >= checkout_date:
                    chkout_dt = chkin_dt + datetime.timedelta(days=1)
                    checkout_date = chkout_dt.replace(hour=13, minute=00, second=00)
                checkout_date_compare = chkout_dt.replace(hour=15, minute=00, second=01)
                checkout_date_dur = chkout_dt.replace(hour=15, minute=00, second=00)
                if checkin_date >= checkout_date_compare:
                    checkin_date = checkout_date_dur - datetime.timedelta(days=1)
                dur = checkout_date_dur - checkin_date
                duration = dur.days
                self.duration=duration
                self.checkin=checkin_date
            else:
                chkout_dt = datetime.datetime.strptime(self.checkout,'%Y-%m-%d %H:%M:%S')
                checkout_date = chkout_dt.replace(hour=13, minute=00, second=00)
            self.checkout=checkout_date

    @api.multi
    def send_booking_mail(self):
        '''
        This function opens a window to compose an email,
        template message loaded by default.
        @param self: object pointer
        '''
        assert len(self._ids) == 1, 'This is for a single id at a time.'
        ir_model_data = self.env['ir.model.data']
        try:
            template_id = (ir_model_data.get_object_reference
                           ('etourism_booking_group',
                            'email_template_booking_group')[1])
        except ValueError:
            template_id = False
        try:
            compose_form_id = (ir_model_data.get_object_reference
                               ('mail',
                                'email_compose_message_wizard_form')[1])
        except ValueError:
            compose_form_id = False
        ctx = dict()
        ctx.update({
            'default_model': 'etourism.booking.group',
            'default_res_id': self._ids[0],
            'default_use_template': bool(template_id),
            'default_template_id': template_id,
            'default_composition_mode': 'comment',
            'force_send': True,
            'mark_so_as_sent': True
        })
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'mail.compose.message',
            'views': [(compose_form_id, 'form')],
            'view_id': compose_form_id,
            'target': 'new',
            'context': ctx,
            'force_send': True
        }


    @api.multi
    def get_num_extra(self, rec_num_people, rec_num_included_occupancy):
        difference, num_extra_beds = 0, 0
        if rec_num_people > rec_num_included_occupancy:
            difference = rec_num_people - rec_num_included_occupancy
            if difference > 0:
                num_extra_beds = difference
        return num_extra_beds

    @api.multi
    def get_num_extra_children(self, rec_num_children, rec_num_adults, rec_num_included_occupancy):
        difference, num_extra_beds = 0, 0
        num_people = rec_num_children + rec_num_adults
        if num_people > rec_num_included_occupancy:
            difference = rec_num_children
            if difference > 0:
                num_extra_beds = difference
        return num_extra_beds

    @api.model
    def create(self, vals):
        print "########################### CREATE BOOKING GROUP ###########################"
        print vals
        """
        Overrides orm create method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        """
        if not vals:
            vals = {}
        if self._context is None:
            self._context = {}
        if 'booking_line' in vals:
            if not vals['booking_line']:
                raise ValidationError('You tried to create reservation without selecting rooms')
        if 'num_adults' in vals:
            if vals['num_adults'] <= 0:
                raise ValidationError(_('Number of adults is mandatory and should be greater than zero.'))
        if 'guest_id' in vals:
            guest_id =vals['guest_id']
            partner_rec = self.env['res.partner'].browse(guest_id)
            vals['guest_email']=partner_rec.email
            vals['guest_country']=partner_rec.country_id.id

        percentage,company_id=0,False
        if 'enterprise_id' in vals:
            enterprise_id=vals['enterprise_id']
            print "ENTERPRISE ID IN VALS::::::::::::::::",enterprise_id
            enterprise = self.env['etourism.enterprise'].search([('id', '=', enterprise_id)], limit=1)
            if enterprise:
                ebusiness_id = enterprise.ebusiness_id.id
                contracts = []
                for contract in enterprise.ebusiness_id.contract_ebusiness_ids:
                    contracts.append(contract.id)
                    
                contract_ids = self.env['ecom.contract'].search([('id','in',contracts)])
                for cont in contract_ids:
                    self._cr.execute("select percentage from ecom_contract  "
                         "where (start_date,end_date) overlaps \
                         ( timestamp %s, timestamp %s ) AND id=%s",
                         (cont.start_date, cont.end_date,cont.id))
                    result = self._cr.fetchall()
                    if result:
                        for res in result:
                            percentage=res[0]
        else:
            print "ELSE::::::::::::::::"
            if 'booking_line' in vals:
                for bk_line in vals['booking_line']:
                    enterprise_id=bk_line[2]['enterprise_id']

        vals['contract_percentage']=percentage
        if 'origin' in vals:
            if vals['origin'] == 'pms':
                vals['state'] = 'confirmed'
            else:
                vals['state'] = 'pending'
        #print "ORIGIN::::::::::::::::",vals['origin']
        #print "STATE::::::::::::::::",vals['state']
        print "ENTERPRISE ID::::::::::::::::",enterprise_id
        enterprise_rec = self.env['etourism.enterprise'].browse(enterprise_id)
        company_id = enterprise_rec.ebusiness_id.company_id.id
        print "COMPANY ID::::::::::::::::::::",company_id
        vals['reservation_no'] = self.env['ir.sequence'].with_context(force_company=company_id).get('etourism.booking.group')
        print "RESERVATION ID::::::::::::::::::::",vals['reservation_no']
        return super(EtourismBookingGroup, self).create(vals)

    @api.multi
    def write(self, vals):
        print "WRITE BOOKING GROUP: ", vals
        """
        Overrides orm write method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        update Hotel Room Reservation line history"""
        checkin=self.checkin
        checkout=self.checkout
        checkout_dur=self.checkout
        grp_total_amount,guest_id = 0.0,False
        if 'checkin' in vals:
            checkin=vals['checkin']

        if 'checkout' in vals:
            checkout = vals['checkout']
            checkout_dur = vals['checkout']
        checkin = datetime.datetime.strptime(checkin, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00, second=00)
        checkout = datetime.datetime.strptime(checkout, '%Y-%m-%d %H:%M:%S').replace(hour=13, minute=00, second=00)
        checkout_dur = datetime.datetime.strptime(checkout_dur, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00, second=00)
        dur = checkout_dur - checkin
        duration = dur.days
        vals['duration']=duration
        checkin_str = checkin.strftime('%Y-%m-%d %H:%M:%S')
        checkout_str = checkout.strftime('%Y-%m-%d %H:%M:%S')

        if checkin > checkout:
            raise ValidationError(_('Checkout Date must be greater then Checkin.'))

        if 'guest_id' in vals:
            guest_id =vals['guest_id']
            partner_rec = self.env['res.partner'].browse(guest_id)
            vals['guest_email']=partner_rec.email
            vals['guest_country']=partner_rec.country_id.id
        if self.booking_line:
            for line_id in self.booking_line:
                extra_bed_amount_adults, extra_bed_amount_children = 0, 0
                checkin_dt = (checkin + datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')
                checkout_dt = (checkout - datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

                self._cr.execute("select count(*) from etourism_booking  "
                         "where (checkin,checkout) overlaps \
                         ( timestamp %s, timestamp %s ) "
                         "and room_id = %s "
                         "and state in ('request','confirmed','pending','checkout','hosted') "
                         ,
                         (checkin_dt,
                          checkout_dt,
                          line_id.room_id.id
                          ))
                res = self._cr.fetchone()
                if res[0] > 1:
                    raise ValidationError(_('You tried to create reservation in room %s that already have been reserved in this period.' % (line_id.room_id.name)))
                if line_id.enterprise_id.use_reductions is False:
                    extra_beds_amount = float(line_id.pricelist_item_id.additional_price * line_id.num_extra_bed) * duration
                else:
                    if line_id.pricelist_item_id.max_adults < line_id.pricelist_item_id.max_occupancy:
                        #print "WRITE INSIDE IF:::::::::::::::::::::::::"
                        num_extra_adults = self.get_num_extra(line_id.num_adults,line_id.pricelist_item_id.max_adults)
                        num_extra_children = self.get_num_extra_children(line_id.num_children,line_id.num_adults,line_id.pricelist_item_id.max_adults)
                        #print "NUM ADULTS:::::::::::::::::::::::::",num_extra_adults
                        #print "NUM CHILDREN:::::::::::::::::::::::::",num_extra_children
                        if num_extra_adults > 0:
                            extra_bed_amount_adults = (line_id.pricelist_item_id.fixed_price * (100 - line_id.pricelist_item_id.pricelist_id.extra_bed_adults) / 100) / 2
                        if num_extra_children == 1:
                            extra_bed_amount_children = (line_id.pricelist_item_id.fixed_price * (100 - line_id.pricelist_item_id.pricelist_id.extra_bed_first_child) / 100) / 2
                        if num_extra_children == 2:
                            extra_bed_amount_children = (line_id.pricelist_item_id.fixed_price * (100 - line_id.pricelist_item_id.pricelist_id.extra_bed_first_child) / 100) / 2
                            extra_bed_amount_children += (line_id.pricelist_item_id.fixed_price * (100 - line_id.pricelist_item_id.pricelist_id.extra_bed_second_child) / 100) / 2

                    extra_amount = extra_bed_amount_adults + extra_bed_amount_children
                    extra_beds_amount = float(extra_amount) * duration
                line_amount = (duration * line_id.unitary_amount) + extra_beds_amount
                line_amount = line_amount - (line_amount * (line_id.discount / (100 * 1.0)))
				
                grp_total_amount = grp_total_amount + line_amount
                self._cr.execute("""UPDATE etourism_booking SET checkin='%s',checkout='%s',duration=%s,amount=%s,extra_beds_amount=%s,checkin_readonly='%s',checkout_readonly='%s',duration_readonly=%s WHERE id=%s"""%(checkin_str,checkout_str,duration,line_amount,extra_beds_amount,checkin_str,checkout_str,duration,line_id.id))
                self._cr.execute("""UPDATE sale_order_line SET product_uom_qty=%s,price_subtotal=%s,price_extra_bed=%s WHERE booking_line_id=%s and product_id in (select p.id from product_product p where p.isroom is true)"""%(duration,line_amount,extra_beds_amount,line_id.id))
                self._cr.execute("""UPDATE etourism_enterprise_folio_line SET checkin_date='%s',checkout_date='%s' WHERE booking_id=%s"""%(checkin_str,checkout_str,line_id.id))
        vals['total_amount']=grp_total_amount
        sale_order_obj = self.env['sale.order'].search([('booking_group_id', '=', self.id)])
        if sale_order_obj:
            for sale in sale_order_obj:
                #self._cr.execute("""UPDATE sale_order SET amount_untaxed=%s,amount_total=%s WHERE booking_group_id=%s"""%(grp_total_amount,grp_total_amount,self.id))
                #print "SALE ORDER ID::::::::::::::::::::::::::::::::::::",sale_order_obj.id
                self._cr.execute("""UPDATE sale_order SET amount_untaxed=(select sum(l.price_subtotal) from sale_order_line l where l.order_id=%s)
		,amount_total=(select sum(l.price_subtotal+l.price_tax) from sale_order_line l where l.order_id=%s) WHERE id=%s"""%(sale.id,sale.id,sale.id))
        if checkin_str and checkout_str:
            self._cr.execute("""UPDATE etourism_enterprise_folio SET checkin_date='%s',checkout_date='%s',duration=%s WHERE booking_group_id=%s"""%(checkin_str,checkout_str,duration,self.id))

        return super(EtourismBookingGroup, self).write(vals)

    @api.multi
    def unlink(self):
        """
        Overrides orm unlink method.
        @param self: The object pointer
        @return: True/False.
        """
        for booking_rec in self:
            if booking_rec.state != 'pending':
                raise ValidationError(_('You cannot delete Reservation in %s\
                state.') % (booking_rec.state))
        return super(EtourismBookingGroup, self).unlink()

    @api.multi
    def get_date(self,rec_date):
        return_date=''
        return_date = time.strftime('%d %b %Y %a',time.strptime(rec_date,'%Y-%m-%d %H:%M:%S'))
        return return_date

    @api.multi
    def get_float_amount(self,rec_amount):
        return_amount=0.0
        return_amount = int(rec_amount)
        str_return_amount = splitthousands(return_amount)
        return str_return_amount

    @api.multi
    def get_subtotal(self):
        total, currency_id = 0.0, False
        for booking in self:
            for line in booking.booking_line:
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                break
            for line in booking.booking_line:
                total += (line.unitary_amount * line.duration)
        total = formatLang(self.env, total, currency_obj=currency_id)
        return total

    @api.multi
    def get_extra_bed_amount(self):
        total, currency_id = 0.0, False
        for booking in self:
            for line in booking.booking_line:
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                break
            for line in booking.booking_line:
                total += (line.extra_beds_amount)
        total = formatLang(self.env, total, currency_obj=currency_id)
        return total

    @api.multi
    def get_total_amount(self):
        currency_id = False
        for booking in self:
            for line in booking.booking_line:
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                break
        total = formatLang(self.env, self.total_amount, currency_obj=currency_id)
        return total

    @api.multi
    def get_amount(self,amount):
        amount_currency,received_amount, currency_id = 0.0,0.0, False
        if amount:
            received_amount=amount
        for booking in self:
            for line in booking.booking_line:
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                break
        amount_currency = formatLang(self.env, received_amount, currency_obj=currency_id)
        return amount_currency


class EtourismBooking(models.Model):
    _name = 'etourism.booking'
    _description = "Booking"
    _rec_name = 'room_id'

    #name = fields.Char(string='Name')
    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise')
    booking_date = fields.Datetime('Booking Date', required=True, readonly=True,
                                 default=(lambda *a:
                                          time.strftime
                                          (DEFAULT_SERVER_DATETIME_FORMAT)))
    checkin = fields.Datetime(string='Checkin')
    checkout = fields.Datetime(string='Checkout')
    duration = fields.Integer(string='Duration')
    room_id = fields.Many2one('etourism.room', 'Room',required=True)
    booking_group_id = fields.Many2one('etourism.booking.group', 'Booking Group',required=True)
    state = fields.Selection([('request', 'Request'),('pending', 'Pending'),
                              ('confirmed', 'Confirmed'),
                              ('no_show', 'No Show'),
                              ('cancelled', 'Cancelled'),
                              ('hosted', 'Checkin'),
                              ('checkout', 'Checkout'),
                              ], 'State', default='request', track_visibility='onchange',translate=False)
    amount = fields.Float('Amount')
    unitary_amount = fields.Float('Unitary Amount')
    #Client tab
    #client_name = fields.Char(string='Client name')
    #client_country = fields.Char(string='Country')
    #client_nationality = fields.Char(string='Nationality')
    #client_email = fields.Char(string='Email')
    #client_phone = fields.Char(string='Phone')
    #client_address = fields.Char(string='Address')
    #client_id_number = fields.Char(string='ID Number')
    #client_motive = fields.Char(string='Motive')
    #enterprise = fields.Char(string='Enterprise Name Import')
    num_adults = fields.Integer(string='Number of adults')
    num_children = fields.Integer(string='Number of children')
    group_id = fields.Integer(string='Group ID')
    online_booking = fields.Boolean(string='Online booking',default=False)
    room_type = fields.Char(string='Room Type')
    #guest_id= fields.Many2one('res.partner', 'Guest Name', readonly=True,states={'confirmed': [('readonly', False)]})
    pricelist_item_id = fields.Many2one('product.pricelist.item', 'Pricelist Item',required=True)
    num_extra_bed = fields.Integer(string='Number of extra beds')
    extra_beds_amount = fields.Float('Extra Beds Amount')

    enterprise_id_readonly = fields.Many2one(related="enterprise_id", string='Enterprise', store=True, readonly=True)
    booking_date_readonly = fields.Datetime(related="booking_date", string='Booking Date', store=True, readonly=True)
    checkin_readonly = fields.Datetime(related="checkin", string='Checkin', store=True, readonly=True)
    checkout_readonly = fields.Datetime(related="checkout", string='Checkout', store=True, readonly=True)
    duration_readonly = fields.Integer(related="duration", string='Duration', store=True, readonly=True)
    booking_condition_id = fields.Many2one('etourism.booking.condition', related="pricelist_item_id.booking_condition_id", string='Booking Condition', store=True)
    guest_ids = fields.Many2many('res.partner', 'etourism_booking_res_partner_rel',
                         'booking_id', 'partner_id',string='Guests')
    origin = fields.Selection(string='Origin', related='booking_group_id.origin', store=True)
    currency_symbol = fields.Char(related="booking_group_id.currency_symbol", string='Currency Symbol')
    folio_line_ids = fields.One2many('etourism.enterprise.folio.line', 'booking_id', string="Folio Lines")
    #JCF - 22-05-2018
    folio_line = fields.One2many('etourism.enterprise.folio', 'booking_id', string="Folio")
    invoice_line = fields.One2many('account.invoice', 'booking_id', string="Invoices")
    #JCF - 30-01-2019
    pricelist_id = fields.Many2one('product.pricelist', 'Pricelist',required=True)
    discount = fields.Float('Discount (%)',default=0.0)

    @api.multi
    def get_num_extra(self, rec_num_people, rec_num_included_occupancy):
        difference, num_extra_beds = 0, 0
        if rec_num_people > rec_num_included_occupancy:
            difference = rec_num_people - rec_num_included_occupancy
            if difference > 0:
                num_extra_beds = difference
        return num_extra_beds

    @api.multi
    def get_num_extra_children(self, rec_num_children, rec_num_adults, rec_num_included_occupancy):
        difference, num_extra_beds, adults_difference = 0, 0, 0
        num_people = rec_num_children + rec_num_adults
        if num_people > rec_num_included_occupancy:
            adults_difference = rec_num_included_occupancy - rec_num_adults
            if adults_difference > 0:
                difference = rec_num_children - adults_difference
            else:
                difference = rec_num_children
            num_extra_beds = difference
        return num_extra_beds

    @api.multi
    def action_no_show(self):
        from_dt = datetime.date.today()
        booking_lines = self.env['etourism.booking']
        checkin = datetime.datetime.strptime(self.checkin, '%Y-%m-%d %H:%M:%S').date()
        if from_dt < checkin:
            raise ValidationError(_('You cannot set a No Show before checkin date.'))
        else:
            self.write({'state': 'no_show'})
            bk_not_selected = booking_lines.sudo().search([('booking_group_id', '=', self.booking_group_id.id),
                                                           ('state', '!=', 'no_show'),('id', '!=', self.id)])
            for b in bk_not_selected:
                print "BOOKING LINES STATES::::::::::::::::", b.state
            if len(bk_not_selected) == 0:
                self.booking_group_id.write({'state': 'no_show'})
            #raise ValidationError(_('No Show Test'))
        return True

    @api.multi
    def action_cancelled(self):
        booking_lines = self.env['etourism.booking']
        self.write({'state': 'cancelled'})
        bk_not_selected = booking_lines.sudo().search([('booking_group_id', '=', self.booking_group_id.id), ('state', '!=', 'cancelled'),
                                                       ('id', '!=', self.id)])
        #print "CANCEL BOOKING GROUP:::::::::::::::",len(bk_not_selected)
        for b in bk_not_selected:
            print "BOOKING LINES STATES::::::::::::::::", b.state
        if len(bk_not_selected) == 0:
            self.booking_group_id.write({'state':'cancelled'})
        #raise ValidationError(_('Cancelar Test'))
        return True

    @api.multi
    def action_hosted(self):
        from_dt = datetime.date.today()
        checkin = datetime.datetime.strptime(self.checkin, '%Y-%m-%d %H:%M:%S').date()
        enterprise_folio_obj = self.env['etourism.enterprise.folio']
        sale_order_obj = self.env['sale.order']
        if from_dt < checkin:
            raise ValidationError(_('You cannot checkin before checkin date.'))
        else:
            folio_lines = []
            checkin_date = self.checkin
            checkout_date = self.checkout
            if not self.booking_group_id.checkin < self.booking_group_id.checkout:
                raise ValidationError(_('Checkout date should be greater than the Checkin date'))
            checkout_date_dur = self.booking_group_id.checkout
            checkout_date_dur = checkout_date_dur.split(' ')[0] + str(' 15:00:00')
            duration_vals = (self.booking_group_id.onchange_check_dates(checkin_date=checkin_date,checkout_date=checkout_date_dur, duration=False))
            duration = duration_vals.get('duration') or 0.0

            booking_pricelist_id = False
            guest_id = False
            guest_id = self.guest_ids[0].id
            date_a = (datetime.datetime(*time.strptime(self.checkout,DEFAULT_SERVER_DATETIME_FORMAT)[:5]))
            date_b = (datetime.datetime(*time.strptime(self.checkin,DEFAULT_SERVER_DATETIME_FORMAT)[:5]))
            if self.pricelist_item_id and self.pricelist_item_id.pricelist_id and not booking_pricelist_id:
                booking_pricelist_id = self.pricelist_item_id.pricelist_id.id
            booking_line_name = self.room_id.product_id and self.room_id.product_id.name or ''
            booking_line_name += self.booking_condition_id and self.booking_condition_id.name or ''
            folio_lines.append((0, 0, {
				'checkin_date': checkin_date,
				'checkout_date': checkout_date,
				'product_id': self.room_id.product_id and self.room_id.product_id.id,
				'name': booking_line_name or '/',
				'product_uom_qty': ((date_a - date_b).days),
				'price_unit': self.unitary_amount,
				'price_extra_bed': self.extra_beds_amount,
				'price_reduce': self.unitary_amount,
				'price_subtotal': self.amount,
				'booking_line_id': self.id,
				'is_reserved': True}))

            folio_vals = {
						'date_order': self.booking_date,
						'enterprise_id': self.enterprise_id.id,
						'partner_id': guest_id,
						'partner_invoice_id': guest_id,
						'partner_shipping_id': guest_id,
						'checkin_date': self.checkin,
						'checkout_date': self.checkout,
						'duration': duration,
						'booking_group_id': self.booking_group_id.id,
						'booking_id': self.id,
						'amount_untaxed': self.amount,
						'amount_total': self.amount,
						'room_lines': folio_lines,
						'state':'draft',
						'pricelist_id': booking_pricelist_id
                    }

            folio = enterprise_folio_obj.create(folio_vals)
            self._cr.execute('insert into enterprise_folio_booking_rel'
                             '(order_id, invoice_id) values (%s,%s)',
                             (self.booking_group_id.id, folio.id))
            sale_order = sale_order_obj.search([('id','=',folio.order_id.id)])
            sale_order.write({'booking_group_id': self.booking_group_id.id,'booking_id': self.id})
            self.write({'state': 'hosted'})
            self.booking_group_id.write({'state': 'hosted'})

        return True

    @api.multi
    def action_checkout(self):
        booking_lines = self.env['etourism.booking']
        self.write({'state': 'checkout'})
        bk_not_selected = booking_lines.sudo().search(
            [('booking_group_id', '=', self.booking_group_id.id), ('state', '!=', 'checkout'),
             ('id', '!=', self.id)])
        for b in bk_not_selected:
            print "BOOKING LINES STATES::::::::::::::::", b.state
        if len(bk_not_selected) == 0:
            self.booking_group_id.write({'state':'checkout'})
        #raise ValidationError(_('Checkout Test'))
        return True

    @api.multi
    def action_create_invoice(self):
        for booking in self:
            folio_id = False
            if self.folio_line:
                for ln in self.folio_line:
                    folio_id = ln.id
                ctx = dict(
						default_booking_id=self.id,
						default_folio_id=folio_id
                )

                return {
					'name': _('Folio lines'),
					'view_type': 'form',
					'view_mode': 'form',
					'res_model': 'etourism.booking.invoice.wizard',
					'view_id': False,
					'type': 'ir.actions.act_window',
					'target': 'new',
                    'context': ctx,
                }

                return self.env['warning'].info(title=_('Success!'), message=_('The invoice was created successfully!!'))
            else:
                return self.env['warning'].info(title=_('Warning!'), message=_('This booking has no folio created yet!!'))

    @api.model
    def create(self, vals):
        print "########################### CREATE BOOKING LINE ###########################: ",vals
        extra_bed_amount_adults,extra_bed_amount_children,num_extra_adults,num_extra_children,booking_amount = 0,0,0,0,0.0
        if not vals:
            vals = {}
        if self._context is None:
            self._context = {}
        if 'room_id' not in vals:
            raise ValidationError(_('You tried to add reservation without selecting a room'))
        if 'pricelist_item_id' not in vals:
            raise ValidationError(_('You tried to add reservation without price list item'))
        if 'enterprise_id' not in vals:
            raise ValidationError(_('You tried to add reservation without enterprise'))
        if 'checkin' not in vals:
            raise ValidationError(_('You tried to add reservation without checkin'))
        if 'checkout' not in vals:
            raise ValidationError(_('You tried to add reservation without checkout'))
        if 'num_adults' not in vals or not vals['num_adults']:
            raise ValidationError(_('You tried to add reservation without num_adults'))
        if 'num_children' not in vals:
            vals['num_children'] = 0

        vals['checkin'] = datetime.datetime.strptime(str(vals['checkin']), '%Y-%m-%d %H:%M:%S').replace(hour=15,minute=00,second=00)
        vals['checkout'] = datetime.datetime.strptime(str(vals['checkout']), '%Y-%m-%d %H:%M:%S').replace(hour=13,minute=00,second=00)

        checkin_dt = (vals['checkin'] + datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

        checkout_dt = (vals['checkout'] - datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

        self._cr.execute("select count(*) from etourism_booking  "
                         "where (checkin,checkout) overlaps \
                         ( timestamp %s, timestamp %s ) "
                         "and room_id = %s "
                         "and state in ('request','confirmed','pending','checkout','hosted') ",
                         (checkin_dt, checkout_dt, vals['room_id']))
        res = self._cr.fetchone()
        if res:
            count = res[0]
        if count > 0:
            raise ValidationError(_('This room already have been reserved in this reservation period.'))
        if 'booking_group_id' not in vals:
            guest=[]
            if vals['guest_ids']:
                #print "#1 LEN GUEST IDS::::::::::::::::::::::::::::::"
                #print len(vals['guest_ids'])
                if len(vals['guest_ids']) == 0:
                    raise ValidationError(_('You tried to add reservation without selecting a guest.'))
                else:
                    guest=vals['guest_ids'][0][2][-1]
            booking_group_id = self.env['etourism.booking.group'].create({
                'enterprise_id': vals['enterprise_id'],
                'checkin': vals['checkin'],
                'checkout': vals['checkout'],
                'guest_id': guest,
                'num_rooms': 1,
                'duration': vals['duration'],
                'num_adults': vals['num_adults'],
                'num_children': vals['num_children'],
                'origin': 'pms'
            })
            booking_group_id.action_confirm_via_planning()
            vals['booking_group_id'] = booking_group_id.id
        if 'booking_group_id' in vals:
            #print "#2 LEN GUEST IDS::::::::::::::::::::::::::::::"
            #print len(vals['guest_ids'])
            if 'guest_ids' in vals:
                if len(vals['guest_ids']) == 0:
                    raise ValidationError(_('You tried to add reservation without selecting a guest.'))

            booking_group_id = self.env['etourism.booking.group'].browse(vals['booking_group_id'])
            pricelist_item_id = self.env['product.pricelist.item'].browse(vals['pricelist_item_id'])

            vals['booking_group_id'] = booking_group_id.id
            vals['checkin'] = booking_group_id.checkin
            vals['checkout'] = booking_group_id.checkout
            vals['checkin_readonly'] = booking_group_id.checkin
            vals['checkout_readonly'] = booking_group_id.checkout
            vals['duration'] = booking_group_id.duration
            vals['duration_readonly'] = booking_group_id.duration
            vals['extra_beds_amount'] = pricelist_item_id.additional_price * booking_group_id.duration * vals['num_extra_bed']

            if pricelist_item_id.enterprise_id.use_reductions is False:
                vals['extra_beds_amount'] = float(pricelist_item_id.additional_price * vals['num_extra_bed']) * booking_group_id.duration
                #print "EXTRA BEDS AMOUNT: ",vals['extra_beds_amount']
            else:
                #print "USE REDUCTIONS TRUE: "
                num_extra_adults = self.get_num_extra(vals['num_adults'],pricelist_item_id.max_adults)
                num_extra_children = self.get_num_extra_children(vals['num_children'],vals['num_adults'],pricelist_item_id.max_adults)
                #print "NUM EXTRA ADULTS: ",num_extra_adults
                #print "NUM EXTRA CHILDREN: ",num_extra_children
                if num_extra_adults > 0:
                    extra_bed_amount_adults = (pricelist_item_id.fixed_price * (100 - pricelist_item_id.pricelist_id.extra_bed_adults) / 100) / 2
                if num_extra_children == 1:
                    extra_bed_amount_children = (pricelist_item_id.fixed_price * (100 - pricelist_item_id.pricelist_id.extra_bed_first_child) / 100) / 2
                if num_extra_children == 2:
                    extra_bed_amount_children = (pricelist_item_id.fixed_price * (100 - pricelist_item_id.pricelist_id.extra_bed_first_child) / 100) / 2
                    extra_bed_amount_children += (pricelist_item_id.fixed_price * (100 - pricelist_item_id.pricelist_id.extra_bed_second_child) / 100) / 2
                #print "ADULTS EXTRA BED AMOUNT: ",extra_bed_amount_adults
                #print "CHILDREN EXTRA BED AMOUNT: ",extra_bed_amount_children
                extra_amount = extra_bed_amount_adults + extra_bed_amount_children
                vals['extra_beds_amount'] = float(extra_amount) * booking_group_id.duration
                #print "EXTRA BED AMOUNT: ",vals['extra_beds_amount']

            booking_amount = vals['duration'] * vals['unitary_amount'] + vals['extra_beds_amount']
            booking_amount = booking_amount - (booking_amount * (vals['discount'] / (100 * 1.0)))
            print "DISCOUNT::::::::::::::::::::::::::::",vals['discount']
            print "BOOKING AMOUNT::::::::::::::::::::::::::::",booking_amount
            vals['amount'] = booking_amount
            if booking_group_id.origin == 'pms':
                vals['state'] = 'confirmed'
            else:
                vals['state'] = 'pending'

        #print "#2 ORIGIN::::::::::::::::",booking_group_id.origin
        #print "#2 STATE::::::::::::::::",vals['state']
        #raise ValidationError('Test2')
        return super(EtourismBooking, self).create(vals)

    @api.multi
    def write(self, vals):
        print "WRITE BOOKING LINE: ", vals
        """
        Overrides orm write method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        update Hotel Room Reservation line history"""
        #if 'checkin' in self :
         #   checkin = self.checkin
        #if 'checkout' in self :
         #   checkout=self.checkout
        total_amount,total_amount_sale_order = 0.0,0.0
        if 'checkin' in vals:
            checkin = vals['checkin']
        else:
            checkin = self.checkin

        if 'checkout' in vals:
            checkout =vals['checkout']
        else:
            checkout = self.checkout
        if 'room_id' in vals:
            room_id = vals['room_id']
        else:
            room_id = self.room_id.id

        if 'duration' in vals:
            duration = vals['duration']
        else:
            duration = self.duration

        if 'unitary_amount' in vals:
            unitary_amount = vals['unitary_amount']
        else:
            unitary_amount = self.unitary_amount

        if 'amount' in vals:
            total_amount = vals['amount']
        else:
            total_amount = self.amount

        room_obj = self.env['etourism.booking'].search([('id','=',room_id)])
        if 'booking_id' in vals:
            print "BALLELE"
            booking_id = vals['booking_id']
        else:
            print "AQUI"
            booking_id = self.id
        print "BOOKINGID WRITE:::::::::::",booking_id
        booking_obj = self.env['etourism.booking'].search([('id', '=',booking_id)])

        if isinstance(checkin, basestring):
            checkin = datetime.datetime.strptime(checkin, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00, second=00)
        if isinstance(checkout, basestring):
            checkout = datetime.datetime.strptime(checkout, '%Y-%m-%d %H:%M:%S').replace(hour=13, minute=00, second=00)

        if checkin > checkout:
            raise ValidationError(_('Checkout Date must be greater then Checkin.'))

        checkin_dt = (checkin + datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

        checkout_dt = (checkout - datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

        self._cr.execute("select count(*) from etourism_booking  "
                         "where (checkin,checkout) overlaps \
                         ( timestamp %s, timestamp %s ) "
                         "and room_id = %s "
                         "and state in ('request','confirmed','pending','checkout','hosted') "
                         ,
                         (checkin_dt,
                          checkout_dt,
                          room_id
                          ))
        res = self._cr.fetchone()
        if res[0] > 1:
            raise ValidationError(_('You tried to create reservation in room %s that already have been reserved in this period.' % (room_obj.room_id.name)))

        folio_line = self.env['etourism.enterprise.folio.line'].search([('booking_id','=',self.id),('is_reserved','=',True)])
        if folio_line:
            print "LINE ID::::::::::::::::: ",folio_line.id
            sale_order_lines = self.env['sale.order.line'].search([('order_id','=',folio_line.folio_id.order_id.id),('id','!=',folio_line.order_line_id.id)])
            total_amount_sale_order = total_amount
            for sl_ln in sale_order_lines:
                total_amount_sale_order += sl_ln.price_subtotal

            self._cr.execute("""UPDATE etourism_enterprise_folio_line SET checkin_date = '%s',checkout_date='%s',room_id=%s WHERE id=%s"""%(checkin, checkout,room_id,folio_line.id))
            self._cr.execute("""UPDATE sale_order_line SET price_unit = %s,product_uom_qty=%s,price_reduce_taxexcl=%s,price_reduce=%s,price_reduce_taxinc=%s,price_subtotal=%s WHERE id=%s"""%(unitary_amount,duration,unitary_amount,unitary_amount,unitary_amount,total_amount,folio_line.order_line_id.id))
            self._cr.execute("""UPDATE etourism_enterprise_folio SET checkin_date = '%s',checkout_date='%s',duration=%s WHERE id=%s"""%(checkin, checkout,duration,folio_line.folio_id.id))
            self._cr.execute("""UPDATE sale_order SET amount_untaxed = %s,amount_total=%s WHERE id=%s"""%(total_amount_sale_order,total_amount_sale_order,folio_line.folio_id.order_id.id))

        if self.id and self.booking_group_id.id:
            booking_lines = self.env['etourism.booking'].search([('id','!=',self.id),('booking_group_id','=',self.booking_group_id.id)])
            checkin_list, checkout_list, duration_list,total_amount_bk_grp = [], [], [],0.0
            checkin_list.append(checkin)
            checkout_list.append(checkout)
            duration_list.append(duration)
            total_amount_bk_grp = total_amount
            for bk_line in booking_lines:
                if isinstance(bk_line.checkin, basestring):
                    checkin = datetime.datetime.strptime(bk_line.checkin, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00, second=00)
                else:
                    checkin = bk_line.checkin
                if isinstance(bk_line.checkout, basestring):
                    checkout = datetime.datetime.strptime(bk_line.checkout, '%Y-%m-%d %H:%M:%S').replace(hour=13, minute=00, second=00)
                else:
                    checkout = bk_line.checkout
                checkin_list.append(checkin)
                checkout_list.append(checkout)
                duration_list.append(duration)
                total_amount_bk_grp += bk_line.amount
        
            booking_group_checkin = min(checkin_list)
            booking_group_checkout = max(checkout_list)
            booking_group_duration = max(duration_list)
            print "GROUP CHECKIN::::::::::::::::: ",booking_group_checkin
            print "GROUP CHECKOUT::::::::::::::::: ",booking_group_checkout
            print "GROUP DURATION::::::::::::::::: ",booking_group_duration
    
            #self.booking_group_id.write({'checkin': booking_group_checkin,'checkout': booking_group_checkout,'duration':booking_group_duration})
            self._cr.execute("""UPDATE etourism_booking_group SET checkin = '%s',checkout='%s',duration=%s,total_amount=%s WHERE id=%s"""%(booking_group_checkin, booking_group_checkout,booking_group_duration,total_amount_bk_grp,self.booking_group_id.id))

        #booking_obj.booking_group_id.onchange_booking_line()
        return super(EtourismBooking, self).write(vals)

    @api.onchange('duration','unitary_amount','extra_beds_amount','discount')
    def _get_amount(self):
        amount = 0.0
        if not self.amount:
            return {}
        amount=(self.duration*self.unitary_amount)+self.extra_beds_amount
        self.amount = amount - (amount * (self.discount / (100 * 1.0))) 


    @api.onchange('checkin','checkout')
    def onchange_dates(self):
        if not (self.checkin and self.checkout):
            return {'value': {}}
        elif self.room_id:
            checkin = datetime.datetime.strptime(self.checkin, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00,second=00)
            checkout = datetime.datetime.strptime(self.checkout, '%Y-%m-%d %H:%M:%S').replace(hour=13, minute=00,second=00)
            checkout_dur = datetime.datetime.strptime(self.checkout, '%Y-%m-%d %H:%M:%S').replace(hour=15, minute=00,second=00)

            if checkin > checkout:
                raise ValidationError(_('Checkout Date must be greater then Checkin.'))
            if checkin < datetime.datetime.now().replace(hour=15, minute=00,second=00,microsecond=00):
                raise ValidationError(_('Checkin date must be greater then today.'))

            checkin_dt = (checkin + datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

            checkout_dt = (checkout - datetime.timedelta(minutes=2)).strftime('%Y-%m-%d %H:%M:%S')

            self._cr.execute("select count(*) from etourism_booking  "
                             "where (checkin,checkout) overlaps \
                             ( timestamp %s, timestamp %s ) "
                             "and room_id = %s "
                             "and state in ('request','confirmed','pending','checkout','hosted') "
                              ,
                             (checkin_dt,
                              checkout_dt,
                              self.room_id.id
                              ))
            res = self._cr.fetchone()
            if res[0] > 1:
                raise ValidationError(_('You tried to create reservation in room %s that already have been reserved in this period.' % (self.room_id.name)))
            self.duration = (checkout_dur-checkin).days
            self.checkin = checkin
            self.checkout = checkout
            if self.pricelist_item_id:
                self.extra_beds_amount = float(self.pricelist_item_id.additional_price * self.num_extra_bed) * self.duration

    @api.onchange('room_id')
    def onchange_room(self):
        #print "ON CHANGE ROOM"
        if not (self.room_id):
            return {'value': {}}
        else:
            self.pricelist_item_id=False
            self.pricelist_id=False

    @api.onchange('pricelist_item_id')
    def onchange_pricelist(self):
        duration=0
        if not (self.pricelist_item_id):
            return {'value': {}}
        else:
            self.onchange_num_adults()
            self.onchange_num_children()
            room_unit_price = self.pricelist_item_id.fixed_price
            duration=self.duration
            self.unitary_amount=room_unit_price
            self.extra_beds_amount=self.pricelist_item_id.additional_price*duration*self.num_extra_bed
            total_price = duration * room_unit_price + self.extra_beds_amount
            total_price = total_price - (total_price * (self.discount / 100))
            self.amount=total_price

    @api.multi
    def get_num_extra_beds(self, rec_num_adults, rec_num_children):
        difference, num_extra_beds, num_people = 0, 0, 0
        num_people = rec_num_adults + rec_num_children
        if num_people <= self.pricelist_item_id.max_occupancy:
            difference = num_people - self.pricelist_item_id.max_adults
            if difference > 0:
                num_extra_beds = difference
        return num_extra_beds

    @api.onchange('num_adults')
    def onchange_num_adults(self):
        difference, num_extra_beds, num_people = 0, 0, 0
        if not self.pricelist_item_id:
            self.num_adults = 0
        else:
            print "IDPRICELIST::::::::::::", self.pricelist_item_id.id
            print "IDPRICELIST-QUANTITY::::::::::::", self.pricelist_item_id.max_adults
            self.num_adults = self.pricelist_item_id.max_adults
            num_people = self.num_adults + self.num_children
            if num_people > self.pricelist_item_id.max_occupancy:
                self.num_adults = 0
                self.num_extra_bed = self.get_num_extra_beds(self.num_adults, self.num_children)
                return {'warning': {
                    'title': 'Max Occupancy Exceeded!',
                    'message': 'Number of people exceeds the maximum occupancy for this room pricelist, which is %s!' % (
                    self.pricelist_item_id.max_occupancy)
                }
                }
            elif num_people <= self.pricelist_item_id.max_occupancy:
                difference = num_people - self.pricelist_item_id.max_adults
                if difference > 0:
                    num_extra_beds = difference
            self.num_extra_bed = num_extra_beds

    @api.onchange('num_children')
    def onchange_num_children(self):
        difference, num_extra_beds, num_people = 0, 0, 0
        if not self.pricelist_item_id:
            self.num_children = 0
        else:
            num_people = self.num_adults + self.num_children
            if num_people > self.pricelist_item_id.max_occupancy:
                self.num_children = 0
                self.num_extra_bed = self.get_num_extra_beds(self.num_adults, self.num_children)
                return {'warning': {
                    'title': 'Max Occupancy Exceeded!',
                    'message': 'Number of people exceeds the maximum occupancy for this room pricelist, which is %s!' % (
                    self.pricelist_item_id.max_occupancy)
                }
                }
            elif num_people <= self.pricelist_item_id.max_occupancy:
                difference = num_people - self.pricelist_item_id.max_adults
                if difference > 0:
                    num_extra_beds = difference
            self.num_extra_bed = num_extra_beds

    @api.onchange('num_extra_bed', 'extra_beds_amount')
    def onchange_num_extra_bed(self):
        if not self.pricelist_item_id:
            self.num_extra_bed = 0
        else:
            pricelist = self.pricelist_item_id
            extra_bed_amount_adults, extra_bed_amount_children = 0, 0
            if (pricelist.max_occupancy <= 0) or (pricelist.max_occupancy == pricelist.max_adults):
                self.num_extra_bed = 0
                self.extra_beds_amount = 0
                return {'warning': {
                                        'title': 'Beds Unavailability!',
                                        'message': 'Currently Extra Beds are not available.'
                                    }
                }
            if pricelist.max_occupancy > pricelist.max_adults:
                allowed_beds = int(pricelist.max_occupancy - pricelist.max_adults)
                if self.num_extra_bed > allowed_beds:
                    bedstring = 'bed is'
                    if allowed_beds > 1:
                        bedstring = 'beds are'
                    self.num_extra_bed = 0
                    self.extra_beds_amount = 0
                    return {'warning': {
                                        'title': 'Beds Unavailability!',
                                        'message': 'Only %s %s allowed to book.'%(str(allowed_beds), bedstring)
                                    }
                    }
                else:
                    if pricelist.enterprise_id.use_reductions is False:
                        self.extra_beds_amount = float(pricelist.additional_price * self.num_extra_bed) * self.duration
                        #print "EXTRA BEDS AMOUNT: ",self.extra_beds_amount
                    else:
                        #print "USE REDUCTIONS TRUE: "
                        num_extra_adults = self.get_num_extra(self.num_adults,pricelist.max_adults)
                        num_extra_children = self.get_num_extra_children(self.num_children,self.num_adults,pricelist.max_adults)
                        #print "NUM EXTRA ADULTS: ",num_extra_adults
                        #print "NUM EXTRA CHILDREN: ",num_extra_children
                        if num_extra_adults > 0:
                            extra_bed_amount_adults = (pricelist.fixed_price * (100 - pricelist.pricelist_id.extra_bed_adults) / 100) / 2
                        if num_extra_children == 1:
                            extra_bed_amount_children = (pricelist.fixed_price * (100 - pricelist.pricelist_id.extra_bed_first_child) / 100) / 2
                        if num_extra_children == 2:
                            extra_bed_amount_children = (pricelist.fixed_price * (100 - pricelist.pricelist_id.extra_bed_first_child) / 100) / 2
                            extra_bed_amount_children += (pricelist.fixed_price * (100 - pricelist.pricelist_id.extra_bed_second_child) / 100) / 2
                        #print "ADULTS EXTRA BED AMOUNT: ",extra_bed_amount_adults
                        #print "CHILDREN EXTRA BED AMOUNT: ",extra_bed_amount_children
                        extra_amount = extra_bed_amount_adults + extra_bed_amount_children
                        self.extra_beds_amount = float(extra_amount) * self.duration

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        """ This function searches for booking lines
        """
        context = self._context or {}
        #print "SEARCH BOOKING LINES::::::::::::::::"
        #print context
        if context and 'filter_current_bookings' in context:
            bookings = []
            if context['filter_current_bookings']:
                enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
                if self.user_has_groups('ecom.group_ecom_hotel') or self.user_has_groups('etourism.group_etourism_directory_tms_operator'):
                    self._cr.execute("""select distinct b.id
from etourism_booking b where b.enterprise_id=%s and b.state in ('hosted','checkout')"""%(enterprise_id.id))
                    result = self._cr.fetchall()
                    if result:
                        for res in result:
                            bookings.append(res[0])
                else:
                    self._cr.execute("""select distinct b.id from etourism_booking b where b.state in ('hosted','checkout')""")
                    result = self._cr.fetchall()
                    if result:
                        for res in result:
                            bookings.append(res[0])

                #bookings = list(set(bookings))

                args.append((('id','in', bookings)))
        return super(EtourismBooking, self).search(args, offset, limit, order, count=count)

    @api.model
    def fields_get(self, fields=None, attributes=None):
        """ Hide fields from advanced search
        """
        fields_to_hide = ['checkin_readonly','checkout_readonly','enterprise_id_readonly','duration_readonly','booking_date_readonly']
        fields = super(EtourismBooking, self).fields_get(fields, attributes=attributes)
        for field in fields_to_hide:
            if field in fields:
                fields[field]['selectable'] = False
        return fields


class EtourismBookingGuest(models.Model):
    _name = 'etourism.booking.guest'
    _rec_name = 'partner_id'
		
    #name = fields.Char(string='Name', required=True)
    booking_id = fields.Many2one('etourism.booking', 'Booking')
    booking_group_id = fields.Many2one('etourism.booking.group', 'Booking Group')
    partner_id = fields.Many2one('res.partner', 'Guest', required=True)
    id_number = fields.Char(related='partner_id.id_number', string='ID Number', store=True)
    reason_travel_id = fields.Many2one('etourism.reason.travel', 'Reason')
    email = fields.Char(related='partner_id.email', string='Email', store=True)
    phone = fields.Char(related='partner_id.phone', string='Phone', store=True)
    mobile = fields.Char(related='partner_id.mobile', string='Mobile', store=True)
    nationality_id = fields.Many2one('res.country', 'Nationality')
    origin_id = fields.Many2one('res.country', 'Place of origin')
    state = fields.Selection(string='State', related='booking_id.state', store=True)


class EtourismNoShowReason(models.Model):
    _name = 'etourism.noshow.reason'
		
    name = fields.Char(string='Name', required=True,translate=True)
    code = fields.Char(string='Code')


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