# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

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

class EtourismBookingCheckin(models.TransientModel):
    _name = 'etourism.booking.checkin.wizard'
    _description = 'Open Booking Checkin Wizard'

    @api.model
    def default_get(self, fields):
        context = self.env.context
        res = super(EtourismBookingCheckin, self).default_get(fields)
        booking_group = self.env['etourism.booking.group'].browse(context.get('active_ids'))
        lines = []
        temp = [lines.append(line.id) for line in booking_group.booking_line if line.state in ('confirmed')]

        res.update(booking_ids=[[6,0, lines]])
        return res

    booking_group_id = fields.Many2one('etourism.booking.group', string='Booking Group')
    booking_ids = fields.Many2many('etourism.booking', 'booking_group_bookings')

    @api.multi
    def action_checkin(self):
        for booking in self:
            booking_group_id=booking.booking_group_id
            enterprise_folio_obj = self.env['etourism.enterprise.folio']
            sale_order_obj = self.env['sale.order']
            if booking.booking_ids:
                for bk in booking.booking_ids:
                    print "BOOKING::::::::::::: ",bk.id
                    folio_lines = []
                    checkin_date = bk.checkin
                    checkout_date = bk.checkout
                    if not booking_group_id.checkin < booking_group_id.checkout:
                        raise ValidationError(_('Checkout date should be greater than the Checkin date'))
                    checkout_date_dur = booking_group_id.checkout
                    checkout_date_dur = checkout_date_dur.split(' ')[0] + str(' 15:00:00')
                    duration_vals = (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
                    print "GUEST IDS:::::::::::::::::::::::::"
                    print bk.guest_ids[0].id
                    guest_id = bk.guest_ids[0].id
                    date_a = (datetime.datetime(*time.strptime(bk.checkout,DEFAULT_SERVER_DATETIME_FORMAT)[:5]))
                    date_b = (datetime.datetime(*time.strptime(bk.checkin,DEFAULT_SERVER_DATETIME_FORMAT)[:5]))
                    if bk.pricelist_item_id and bk.pricelist_item_id.pricelist_id and not booking_pricelist_id:
                        booking_pricelist_id = bk.pricelist_item_id.pricelist_id.id
                    booking_line_name = bk.room_id.product_id and bk.room_id.product_id.name or ''
                    booking_line_name += bk.booking_condition_id and bk.booking_condition_id.name or ''
                    folio_lines.append((0, 0, {
						'checkin_date': checkin_date,
						'checkout_date': checkout_date,
						'product_id': bk.room_id.product_id and bk.room_id.product_id.id,
						'name': booking_line_name or '/',
						'product_uom_qty': ((date_a - date_b).days),
						'price_unit': bk.unitary_amount,
						'discount': bk.discount,
						'price_extra_bed': bk.extra_beds_amount,
						'price_reduce': bk.unitary_amount,
						'price_subtotal': bk.amount,
						'booking_line_id': bk.id,
						'is_reserved': True}))

                    folio_vals = {
						'date_order': bk.booking_date,
						'enterprise_id': bk.enterprise_id.id,
						'partner_id': guest_id,
						'partner_invoice_id': guest_id,
						'partner_shipping_id': guest_id,
						'checkin_date': bk.checkin,
						'checkout_date': bk.checkout,
						'duration': duration,
						'booking_group_id': bk.booking_group_id.id,
						'booking_id': bk.id,
						'amount_untaxed': bk.amount,
						'amount_total': bk.amount,
						'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)',
                             (bk.booking_group_id.id, folio.id))
                    sale_order = sale_order_obj.search([('id','=',folio.order_id.id)])

                    sale_order.write({'booking_group_id': bk.booking_group_id.id,'booking_id': bk.id})
                    #bk.write({'state': 'hosted'})
                    self._cr.execute("""UPDATE etourism_booking SET state = 'hosted' WHERE id=%s"""%(bk.id))
                    #booking.write({'has_folio': True})

            booking_group_id.write({'state': 'hosted'})
