# -*- coding: utf-8 -*-
##############################################################################
#
#    Odoo, Open Source Management Solution
#    Copyright (C) 2016-TODAY Prime Consulting SA, Cape Verde (<http://prime.cv>).
#
##############################################################################
import json
import logging

from odoo import models, api
import urlparse
from datetime import datetime
import sys, os
from bs4 import BeautifulSoup
_logger = logging.getLogger(__name__)

def htmlToText(htmltext):
    soup = BeautifulSoup(htmltext)

    # kill all script and style elements
    for script in soup(["script", "style"]):
        script.extract()    # rip it out

    # get text
    text = soup.get_text()

    # break into lines and remove leading and trailing space on each
    lines = (line.strip() for line in text.splitlines())
    # break multi-headlines into a line each
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    # drop blank lines
    text = '\n'.join(chunk for chunk in chunks if chunk)
    return text

class ResUsers(models.Model):
    _inherit = "res.users"

    @api.multi
    def get_image_url(self, model, field, rec_id):
        url = ''
        if model and rec_id:
            base_url = self.env['ir.config_parameter'].get_param('web.base.url')
            url = "%s" % urlparse.urljoin(base_url, 'web/image/%s/%s/%s'%(model, rec_id, field))
        return url

    @api.model
    def get_fares(self, checkin_date, checkout_date, enterprise_id=0, all_enterprises=False, agency_code=False):
        """Get result from view_fares view
        :params checkin_date: Check In Date
        :params checkout_date: Check Out Date
        :params enterprise_id: ID of the Enterprise (object = etourism.enterprise)
        :return: list of dictionaries
        :rtype: list
        """
        context = self._context
        result, res2 = [], []
        agency_discount = 0.0
        #_logger.debug('FARES HOTEL ID::::::::::::::::::::::::::::::::::::::::::::: %s',enterprise_id)
        #_logger.debug('FARES AGENCY CODE::::::::::::::::::::::::::::::::::::::::::::: %s',agency_code)

        if checkin_date and checkout_date and enterprise_id and agency_code =='NONE':
            #_logger.debug('#1 IF:::::::::::::::::::::::::::::::::::::::::::::')
            self._cr.execute("""select v2.*,(select rooms_availability_by_categ('%s','%s',%s,v2.room_type_id)) as num_rooms_categ 
                                    from (select v.*,rooms_availability_no_limit('%s', '%s', %s, v.room_type_id) as num_rooms 
                                from view_fares v 
                                where v.enterprise_id=%s and '%s' between v.start_date and v.end_date) v2 where v2.num_rooms > 0 order by v2.room_type_id;"""%(checkin_date, checkout_date, enterprise_id,checkin_date, checkout_date, enterprise_id, enterprise_id, checkin_date)
                            )
            result = self._cr.dictfetchall()
            for res in result:
                for i in res:
                    if res[i] is None:
                        res[i] = False
                    if str(i) == 'additional_price' and res[i] is False:
                        res[i] = '--'
        elif checkin_date and checkout_date and enterprise_id and agency_code !='NONE':
            #_logger.debug('#2 ELIF:::::::::::::::::::::::::::::::::::::::::::::')
            self._cr.execute("""select pa.discount 
from product_pricelist p, etourism_pricelist_agency pa
where p.id=pa.pricelist_id and p.enterprise_id=%s and pa.code='%s' and (p.start_date,p.end_date) overlaps ('%s','%s') limit 1
;"""%(enterprise_id,agency_code,checkin_date, checkout_date)
                            )
            agency = self._cr.fetchone()
            if agency:
                agency_discount = agency[0]

            view_query = """select v2.id,v2.enterprise_id,v2.name_enterprise,v2.country_id,v2.island_id,v2.parish_id,v2.island,v2.county,v2.parish,v2.site,v2.ebusiness_id,v2.room_type_id
,v2.name_room_type,v2.condition_id,v2.name_condition,v2.price_item_id,v2.max_adults,v2.max_children,v2.max_occupancy,v2.additional_price,v2.num_adults
,v2.comment,v2.type_id,v2.enterprise_type_id,v2.name_type_ebusiness,v2.name_type_enterprise,v2.start_date,v2.end_date,v2.publish_online,v2.policies
,v2.api_key,v2.rating,v2.local_id,v2.local,v2.neighborhood_id,v2.neighborhood,v2.our_site,v2.comment_en,v2.policies_en,v2.latitude,v2.longitude,v2.featured
,v2.code_island,v2.code_county,v2.comment_fr,v2.policies_fr,v2.currency_symbol,v2.use_reductions,v2.pricelist_id
,(select v2.amount - (v2.amount * (%s / 100.0))) as amount
,(select rooms_availability_by_categ('%s','%s',%s,v2.room_type_id)) as num_rooms_categ,v2.num_rooms
                                    from (select v.*,rooms_availability_no_limit('%s', '%s', %s, v.room_type_id) as num_rooms 
                                from view_fares v 
                                where v.enterprise_id=%s and '%s' between v.start_date and v.end_date) v2 where v2.num_rooms > 0 order by v2.room_type_id;"""%(agency_discount,checkin_date, checkout_date, enterprise_id,checkin_date, checkout_date, enterprise_id, enterprise_id, checkin_date)
            #_logger.debug('VIEW QUERY::::::::::::::::::::::::::::::::::::::::::::: %s',view_query)

            self._cr.execute("""select v2.id,v2.enterprise_id,v2.name_enterprise,v2.country_id,v2.island_id,v2.parish_id,v2.island,v2.county,v2.parish,v2.site,v2.ebusiness_id,v2.room_type_id
,v2.name_room_type,v2.condition_id,v2.name_condition,v2.price_item_id,v2.max_adults,v2.max_children,v2.max_occupancy,v2.additional_price,v2.num_adults
,v2.comment,v2.type_id,v2.enterprise_type_id,v2.name_type_ebusiness,v2.name_type_enterprise,v2.start_date,v2.end_date,v2.publish_online,v2.policies
,v2.api_key,v2.rating,v2.local_id,v2.local,v2.neighborhood_id,v2.neighborhood,v2.our_site,v2.comment_en,v2.policies_en,v2.latitude,v2.longitude,v2.featured
,v2.code_island,v2.code_county,v2.comment_fr,v2.policies_fr,v2.currency_symbol,v2.use_reductions,v2.pricelist_id
,(select v2.amount - (v2.amount * (%s / 100.0))) as amount
,(select rooms_availability_by_categ('%s','%s',%s,v2.room_type_id)) as num_rooms_categ,v2.num_rooms
                                    from (select v.*,rooms_availability_no_limit('%s', '%s', %s, v.room_type_id) as num_rooms 
                                from view_fares v 
                                where v.enterprise_id=%s and '%s' between v.start_date and v.end_date) v2 where v2.num_rooms > 0 order by v2.room_type_id;"""%(agency_discount,checkin_date, checkout_date, enterprise_id,checkin_date, checkout_date, enterprise_id, enterprise_id, checkin_date)
                            )
            result = self._cr.dictfetchall()
            for res in result:
                for i in res:
                    if res[i] is None:
                        res[i] = False
                    if str(i) == 'additional_price' and res[i] is False:
                        res[i] = '--'
        for res in result:
            if isinstance(res, dict):
                if 'room_type_id' in res and 'enterprise_id' in res:
                    rooms = self.env['etourism.room'].search_read([('categ_id','=',int(res['room_type_id'])), 
                                                                   ('enterprise_id','=',int(enterprise_id))],
                                                                fields=['id','image'])
                    image_url = ''
                    for room in rooms:
                        if room['image']:
                            image_url = self.get_image_url('etourism.room', 'image', room['id'])
                            break
                        #for line in room.images:
                        #    if line.image:
                        #        rooms_line.append(line.image)
                    res['image_url'] = image_url
        #_logger.debug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::')
        #_logger.debug('%s',result)
        #_logger.debug(':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::')
        return result


    @api.model
    def get_enterprise_fares(self, checkin_date, checkout_date, enterprise_id=0, agency_code=False):
        """Get result from view_fares view
        :params checkin_date: Check In Date
        :params checkout_date: Check Out Date
        :params enterprise_id: ID of the Enterprise (object = etourism.enterprise)
        :return: list of dictionaries
        :rtype: list
        """
        context = self._context
        fares, result = [], {}
        agency_discount = 0.0

        def get_enterprise_details_from_fares(rooms_availability):
            """Format enterprise info from all rooms_availability related to same enterprise
            """
            line_check = True
            min_amount = 0
            room_image = ''
            agency_discount = 0.0
            for rooms in rooms_availability:
                if line_check:
                    line_check = False
                    min_amount = rooms.get('amount', 0)
                    room_type_id = rooms.get('room_type_id', 0)

                    name_enterprise = rooms['name_type_enterprise']
                    if 'name_enterprise' in rooms:
                        name_enterprise = rooms['name_enterprise']
                    name_type_enterprise = rooms['name_type_enterprise']
                    site = rooms.get('site', '')
                    our_site = rooms.get('our_site', False)
                    api_key = rooms.get('api_key', '')
                    parish_id = rooms.get('parish_id', False)
                    latitude = rooms.get('latitude', False)
                    longitude = rooms.get('longitude', False)
                    if parish_id:
                        parish_id = self.env['ecom.location'].browse([parish_id])[0].name
                    local_id = rooms.get('local_id', False)
                    if local_id:
                        local_id = self.env['ecom.location'].browse([local_id])[0].name
                    neighborhood_id = rooms.get('neighborhood_id', False)
                    if neighborhood_id:
                        neighborhood_id = self.env['ecom.location'].browse([neighborhood_id])[0].name
                    rating = rooms.get('rating', 0)
                    featured = rooms.get('featured', 0)
                    code_island = rooms.get('code_island', '')
                    code_county = rooms.get('code_county', '')
                    currency_symbol = rooms.get('currency_symbol', '')

                    enterprise_id = rooms.get('enterprise_id', '')
                    enterprise_logo = False
                    if enterprise_id:
                        enterprise_logo = self.get_image_url('etourism.enterprise', 'logo', enterprise_id)
                else:
                    room_amount = rooms.get('amount', 0)
                    if room_amount and room_amount < min_amount:
                        room_type_id = rooms.get('room_type_id', 0)
                        min_amount = room_amount

            #get amenities from rooms:
            amenities = []
            if room_type_id and enterprise_id:
                #set room image:
                rooms = self.env['etourism.room'].search_read([('categ_id','=',int(room_type_id)), ('enterprise_id','=', int(enterprise_id))], fields=['id'])
                for room in rooms:
                    room_image = self.get_image_url('etourism.room', 'image', room['id'])

                '''rooms = self.env['etourism.room'].search([('categ_id','=',int(room_type_id)), ('enterprise_id','=', int(enterprise_id))])
                for room in rooms:
                    for am in room.amenities_ids:
                        amenities.append(am.name)'''
                images_count = 0
                enterp = self.env['etourism.enterprise'].search([('id','=', int(enterprise_id))], limit=1)
                if enterp:
                    if enterp.amenities_ids:
                        for amenity in enterp.amenities_ids:
                            if amenity.image_url and images_count < 5:
                                amenities_icons = {}
                                amenity_name = amenity.name
                                amenity_image_url = amenity.image_url
                                amenities_icons = {
									'name':amenity_name,
									'image_url':amenity_image_url
                                }
                                amenities.append(amenities_icons)
                                images_count += 1

            #amenities = list(set(amenities))

            Enterprise = self.env['etourism.enterprise'].search_read([('id','=',enterprise_id)], fields=['comment','comment_en','comment_fr'])[0]
            enterprise_description,enterprise_description_en,enterprise_description_fr='','',''
            if Enterprise['comment']:
                enterprise_description=htmlToText(Enterprise['comment'])
            if Enterprise['comment_en']:
                enterprise_description_en=htmlToText(Enterprise['comment_en'])
            if Enterprise['comment_fr']:
                enterprise_description_fr=htmlToText(Enterprise['comment_fr'])

            enterprise_info = {
                'name_type_enterprise': name_type_enterprise,
                'name_enterprise': name_enterprise,
                'site': site,
                'our_site': our_site,
                'api_key': api_key,
                'parish':parish_id,
                'local':local_id,
                'neighborhood':neighborhood_id,
                'rating':rating,
                'featured':featured,
                'code_island':code_island,
                'code_county':code_county,
                'currency_symbol':currency_symbol,
                'logo': enterprise_logo or '',
                'amount': min_amount,
                'info': {
                    #'policies': Enterprise['policies'],
                    'description': enterprise_description,
                    'description_en': enterprise_description_en,
                    'description_fr': enterprise_description_fr,
                    'photos': [room_image],
                    'amenities': amenities
                },
                'locations': {
                    'long': longitude,
                    'lat': latitude
                },
            }
            return enterprise_info

        if checkin_date and checkout_date and enterprise_id and agency_code=='NONE':
            #_logger.debug('#1 IF:::::::::::::::::::::::::::::::::::::::::::::')

            self._cr.execute("""select v2.*,(select rooms_availability_by_categ('%s','%s',%s,v2.room_type_id)) as num_rooms_categ 
                                    from (select v.*,rooms_availability_no_limit('%s', '%s', %s, v.room_type_id) as num_rooms 
                                from view_fares v 
                                where v.enterprise_id=%s and '%s' between v.start_date and v.end_date) v2 where v2.num_rooms > 0 order by v2.room_type_id;
                                """ % 
                                (checkin_date, checkout_date, enterprise_id,checkin_date, checkout_date, enterprise_id, enterprise_id, checkin_date)
                            )
            fares = self._cr.dictfetchall()
            for res in fares:
                for i in res:
                    if res[i] is None:
                        res[i] = False
                    if str(i) == 'additional_price' and res[i] is False:
                        res[i] = '--'
        elif checkin_date and checkout_date and enterprise_id and agency_code!='NONE':
            #_logger.debug('#2 IF:::::::::::::::::::::::::::::::::::::::::::::')
            self._cr.execute("""select pa.discount 
from product_pricelist p, etourism_pricelist_agency pa
where p.id=pa.pricelist_id and p.enterprise_id=%s and pa.code='%s' and (p.start_date,p.end_date) overlaps ('%s','%s') limit 1
;"""%(enterprise_id,agency_code,checkin_date, checkout_date)
                            )
            agency = self._cr.fetchone()
            if agency:
                agency_discount = agency[0]

            self._cr.execute("""select v2.id,v2.enterprise_id,v2.name_enterprise,v2.country_id,v2.island_id,v2.parish_id,v2.island,v2.county,v2.parish,v2.site,v2.ebusiness_id,v2.room_type_id
,v2.name_room_type,v2.condition_id,v2.name_condition,v2.price_item_id,v2.max_adults,v2.max_children,v2.max_occupancy,v2.additional_price,v2.num_adults
,v2.comment,v2.type_id,v2.enterprise_type_id,v2.name_type_ebusiness,v2.name_type_enterprise,v2.start_date,v2.end_date,v2.publish_online,v2.policies
,v2.api_key,v2.rating,v2.local_id,v2.local,v2.neighborhood_id,v2.neighborhood,v2.our_site,v2.comment_en,v2.policies_en,v2.latitude,v2.longitude,v2.featured
,v2.code_island,v2.code_county,v2.comment_fr,v2.policies_fr,v2.currency_symbol,v2.use_reductions,v2.pricelist_id
,(select v2.amount - (v2.amount * (%s / 100.0))) as amount
,(select rooms_availability_by_categ('%s','%s',%s,v2.room_type_id)) as num_rooms_categ 
                                    from (select v.*,rooms_availability_no_limit('%s', '%s', %s, v.room_type_id) as num_rooms 
                                from view_fares v 
                                where v.enterprise_id=%s and '%s' between v.start_date and v.end_date) v2 where v2.num_rooms > 0 order by v2.room_type_id;"""%(agency_discount,checkin_date, checkout_date, enterprise_id,checkin_date, checkout_date, enterprise_id, enterprise_id, checkin_date)
                            )
            fares = self._cr.dictfetchall()
            for res in fares:
                for i in res:
                    if res[i] is None:
                        res[i] = False
                    if str(i) == 'additional_price' and res[i] is False:
                        res[i] = '--'

        if fares:
            result = get_enterprise_details_from_fares(fares)
        return result

    @api.model
    def enterprise_group_availability(self, checkin_date, checkout_date, hotelId=False):
        """Hotels availability for all Enterprises
        """
        context = self._context
        result, res2 = [], []
        
        if hotelId:
            fares = self.get_fares(checkin_date, checkout_date, enterprise_id=hotelId)
            if fares:
                result = self.get_hotel_rooms_list(fares, hotelId)

        if not hotelId or hotelId == 'all':
            #get all islands:
            islands = self.env['ecom.location'].search_read([('level','=','2')], fields=['id','name','code'])
            for island in islands:
                enterprises = []
                island_enterprises = self.env['etourism.enterprise'].search_read([('island_id', '=', island['id']), 
                                                                                  ('ebusiness_type_code', '=', 'ALO'),('id', '<>', 723),
                                                                                  ('ebusiness_state', '=', 'online')], 
                                                                                  fields=['id'])
                for enterprise in island_enterprises:
                    enterprise_info = self.get_enterprise_fares(checkin_date, checkout_date, enterprise_id=enterprise['id'],)
                    if enterprise_info:
                        enterprises.append(enterprise_info)
                
                if enterprises:
                    island_res = {
                        'id': island['id'],
                        'island': island['name'],
                        'code_island': island['code'],
                        'number_enterprise': len(enterprises),
                        'enterprises': enterprises
                    }
                    result.append(island_res)
        result2 = self._prepare_api_response(result, hotelId)
        return result2

    @api.model
    def get_hotel_rooms_list(self, fares, hotelId,agency_code=False):
        rooms_list, hotel_policy, hotel_policy_en,hotel_policy_fr,use_reductions = [], False, False, False,False
        room_type_ids = []
        for room in fares:
            if not hotel_policy:
                hotel_policy = room.get('policies', '')
            if not hotel_policy_en:
                hotel_policy_en = room.get('policies_en', '')
            if not hotel_policy_fr:
                hotel_policy_fr = room.get('policies_fr', '')
            if not use_reductions:
                use_reductions = room.get('use_reductions', False)

            room_type_id = room.get('room_type_id', 0)
            if room_type_id and room_type_id not in room_type_ids:
                room_type_ids.append(room_type_id)
                myList,id_room=[],False
                #myURLs=''
                rooms2 = self.env['etourism.room'].search_read([('categ_id','=',room_type_id), ('enterprise_id','=', hotelId)], fields=['id'],limit=5)
                for room2 in rooms2:
                    myList.append(self.get_image_url('etourism.room', 'image', room2['id']))
                    id_room = room2['id']
                #myURLs = ",".join(myList)
                #image_URL.append(myURLs)
                #print "MY LIST::::::::::::::::::::::::"
                #print myList
                rooms_amenities, images_count = [], 0
                if id_room:
                    room_src = self.env['etourism.room'].search([('id','=', id_room)], limit=1)
                    #print "ID ROOM::::::::::::::::::::::::"
                    #print id_room
                    if room_src:
                        #print "IF ROOM SRC::::::::::::::::::::::::"
                        if room_src.amenities_ids:
                            for amenity in room_src.amenities_ids:
                                if amenity.image_url and images_count < 5:
                                    rooms_amenities_icons = {}
                                    amenity_name = amenity.name
                                    amenity_image_url = amenity.image_url
                                    rooms_amenities_icons = {
										'name':amenity_name,
										'image_url':amenity_image_url
                                    }
                                    rooms_amenities.append(rooms_amenities_icons)
                                    images_count += 1

                #print "NAME:::::::::::::::::::::::"
                #print room.get('name_room_type', '')
                details = {
                    'id': room.get('room_type_id', 0),
                    'name': room.get('name_room_type', ''),
                    'num_rooms': room.get('num_rooms', 0),
                    #'image_url': room.get('image_url', ''),
                    'image_url': myList,
					'amenities': rooms_amenities
                }

                booking_mode, pricelist_ids = [], []
                room_type_id = room.get('room_type_id', 0)
                today = datetime.now().date()

                pricelists = self.env['product.pricelist'].search_read([('enterprise_id', '=', hotelId), ('start_date', '<=', today), ('end_date', '>=', today), ('online_pricelist', '=', True)],
                                                            fields=['id'])
                currency_symbol = ''
                extra_bed_adults, extra_bed_first_child, extra_bed_second_child, extra_bed_infant,id_pricelist = 0,0,0,0,False
                for pricelist in pricelists:
                    pricelist_ids.append(pricelist['id'])
                    #print "ID PRICELIST::::::::::::::::::::::::::::::::::::::::::::::::: ",pricelist['id']
                    _logger.debug('PRICELIST ID:::::::::::::::::::::::::::::::::::::::::::::: %s', pricelist['id'])
                    pricelist_list = self.env['product.pricelist'].sudo().search([('id', '=',pricelist['id'])], limit=1)
                    if pricelist_list:
                        currency_symbol = pricelist_list.currency_id.symbol
                        extra_bed_adults = pricelist_list.extra_bed_adults
                        extra_bed_first_child = pricelist_list.extra_bed_first_child
                        extra_bed_second_child = pricelist_list.extra_bed_second_child
                        extra_bed_infant = pricelist_list.extra_bed_infant
                        id_pricelist = pricelist_list.id
 
                agency_discount = 0.0
                #_logger.debug('AGENCY CODE:::::::::::::::::::::::::::::::::::::::::::::: %s', agency_code)
                if agency_code!='NONE':
                    pricelist_agency = self.env['etourism.pricelist.agency'].sudo().search([('pricelist_id', '=',id_pricelist),('code', '=',agency_code)], limit=1)
                    if pricelist_agency:
                        agency_discount = pricelist_agency.discount
                #_logger.debug('AGENCY DISCOUNT:::::::::::::::::::::::::::::::::::::::::::::: %s', agency_discount)

                if room_type_id:
                    pricelist_items = self.env['product.pricelist.item'].search_read([('categ_id', '=', room_type_id), ('pricelist_id', 'in', pricelist_ids)])
                    for item in pricelist_items:
                        myImagesList=[]
                        rooms_images = self.env['etourism.pricelist.item.image'].search_read([('pricelist_item_id','=',item.get('id', 0))], fields=['id'],limit=5)
                        for rm_img in rooms_images:
                            myImagesList.append(self.get_image_url('etourism.pricelist.item.image', 'image', rm_img['id']))
                        condition_name = item['booking_condition_id'] and item['booking_condition_id'][1] or ''
                        amount_room = item.get('fixed_price', 0) - (item.get('fixed_price', 0) * (agency_discount / (100 * 1.0)))
                        amount_extra_bed = item.get('additional_price', 0) - (item.get('additional_price', 0) * (agency_discount / (100 * 1.0)))
                        _logger.debug('AMOUNT ROOM:::::::::::::::::::::::::::::::::::::::::::::: %s', amount_room)
                        _logger.debug('AMOUNT EXTRA BED:::::::::::::::::::::::::::::::::::::::::::::: %s', amount_extra_bed)
                        booking_mode.append({
                                'price_item_id': item.get('id', 0),
                                'name': condition_name,
                                'currency_symbol': currency_symbol,
                                'max_adults': item.get('max_adults', 0),
                                'max_occupancy': item.get('max_occupancy', 0),
                                'amount': amount_room,
                                'additional_price': amount_extra_bed,
                                'images': myImagesList,
                              })
                details['booking_mode'] = booking_mode
                rooms_list.append(details)
        
        return rooms_list and {'roomsList': rooms_list, 'policies': hotel_policy, 'policies_en': hotel_policy_en, 'policies_fr': hotel_policy_fr,'use_reductions': use_reductions,'reductions': {'extra_bed_adults': extra_bed_adults,'extra_bed_first_child': extra_bed_first_child,'extra_bed_second_child': extra_bed_second_child,'extra_bed_infant': extra_bed_infant}} or {}

    @api.model
    def get_island_id_from_name(self, island_name=''):
        result = False
        if island_name:
            island = self.env['ecom.location'].search_read([('name','=',island_name), ('level','=','2')], fields=['id'], limit=1)
            if island:
                result = island[0]['id']
        return result

    @api.model
    def get_island_id_from_code(self, island_code=''):
        result = False
        if island_code:
            island = self.env['ecom.location'].search_read([('code','=',island_code), ('level','=','2')], fields=['id'], limit=1)
            if island:
                result = island[0]['id']
        return result

    @api.model
    def get_island_name_from_code(self, island_code=''):
        result = False
        if island_code:
            island = self.env['ecom.location'].search_read([('code','=',island_code), ('level','=','2')], fields=['name'], limit=1)
            if island:
                result = island[0]['name']
        return result

    @api.model
    def enterprise_availability(self, checkin_date, checkout_date, island_code=False, hotelId=False,agency_code=False):
    #def enterprise_availability(self, checkin_date, checkout_date, island_name=False, hotelId=False):
        result, result2, island_id = [], {}, False
        _logger.debug('ENTERPRISE AVAILABILITY::::::::::::::::::::::::::::::::::::::::::::::')
        _logger.debug('CHECKIN DATE:::::::::::::::::::::::::::::::::::::::::::::: %s', checkin_date)
        _logger.debug('CHECKOUT DATE:::::::::::::::::::::::::::::::::::::::::::::: %s', checkout_date)
        split_checkin_date = checkin_date.split(" ")
        split_checkout_date = checkout_date.split(" ")
        checkin_date = split_checkin_date[0] + ' 15:00:00'
        checkout_date = split_checkout_date[0] + ' 13:00:00'
        if not checkin_date or not checkout_date:
            result2 = self._prepare_api_response(result, hotelId)
            return result2

        #if island_name:
        #    island_id = self.get_island_id_from_name(island_name)
        if island_code:
            island_id = self.get_island_id_from_code(island_code)
            island_name = self.get_island_name_from_code(island_code)
        else:
            island_id = ''
            island_name = ''

        #print "HOTEL ID:::::::::::::::::::::::::::::",hotelId
        #print "ISLAND ID:::::::::::::::::::::::::::::",island_id
        #print "AGENCY CODE:::::::::::::::::::::::::::::",agency_code
        _logger.debug('HOTEL ID:::::::::::::::::::::::::::::::::::::::::::::: %s', hotelId)
        _logger.debug('ISLAND ID:::::::::::::::::::::::::::::::::::::::::::::: %s', island_id)
        _logger.debug('AGENCY CODE:::::::::::::::::::::::::::::::::::::::::::::: %s', agency_code)

        if (island_id and hotelId and (agency_code=='NONE')) or (not island_id and hotelId and (agency_code=='NONE')):
            #_logger.debug('#1:::::::::::::::::::::::::::::::::::::::::::::')
            #print "#1:::::::::::::::::::::::::::::::::::::::"
            fares = self.get_fares(checkin_date, checkout_date, enterprise_id=hotelId)
            if fares:
                #print "IF FARES:::::::::::::::::::::::::::::::::::::::"
                result = self.get_hotel_rooms_list(fares, hotelId,agency_code=agency_code)
                result2 = self._prepare_api_response(result, hotelId)

        elif island_id and not hotelId and agency_code=='NONE':
            #print "#2:::::::::::::::::::::::::::::::::::::::"
            _logger.debug('#2:::::::::::::::::::::::::::::::::::::::::::::')

            enterprises = []
            island_enterprises = self.env['etourism.enterprise'].search_read([('island_id', '=', island_id), 
                                                                              ('ebusiness_type_code', '=', 'ALO'),('id', '<>', 723),
                                                                              ('ebusiness_published', '=', True)], 
                                                                              fields=['id'])
            for enterprise in island_enterprises:
                enterprise_info = self.get_enterprise_fares(checkin_date, checkout_date, enterprise_id=enterprise['id'])
                if enterprise_info:
                    enterprises.append(enterprise_info)
            
            if enterprises:
                island_res = {
                    'id': island_id,
                    'island': island_name,
                    'island_code': island_code,
                    'number_enterprise': len(enterprises),
                    'enterprises': enterprises
                }
                result.append(island_res)
            result2 = self._prepare_api_response(result, hotelId)

        elif not island_id and not hotelId and (island_code == 'TODAS' or island_code == '') and agency_code=='NONE':
            #print "#3:::::::::::::::::::::::::::::::::::::::"
            #_logger.debug('#3:::::::::::::::::::::::::::::::::::::::::::::')
            result2 = self.enterprise_group_availability(checkin_date, checkout_date)
        elif not island_id and not hotelId and agency_code!='NONE':
            agency_enterprises = []
            enterprises = []
            #print "#4:::::::::::::::::::::::::::::::::::::::"
            #_logger.debug('#4:::::::::::::::::::::::::::::::::::::::::::::')

            self._cr.execute("""select p.enterprise_id 
from product_pricelist p, etourism_pricelist_agency pa
where p.id=pa.pricelist_id and pa.code='%s' and (p.start_date,p.end_date) overlaps ('%s','%s')
;"""%(agency_code,checkin_date, checkout_date)
                            )
            ag_enterprises = self._cr.fetchall()
            for ent in ag_enterprises:
                agency_enterprises.append(ent[0])
            _logger.debug('#AGENCY ENTERPRISES::::::::::::::::::::::::::::::::::::::::::::: %s',agency_enterprises)
            #get all islands:
            islands = self.env['ecom.location'].search_read([('level','=','2')], fields=['id','name','code'])
            for island in islands:
                enterprises = []

                island_enterprises = self.env['etourism.enterprise'].search_read([('island_id', '=', island['id']),('id', 'in', agency_enterprises), 
                                                                              ('ebusiness_type_code', '=', 'ALO'),
                                                                              ('ebusiness_published', '=', True)], 
                                                                              fields=['id'])

                for enterprise in island_enterprises:
                    enterprise_info = self.get_enterprise_fares(checkin_date, checkout_date, enterprise_id=enterprise['id'],agency_code=agency_code)
                    if enterprise_info:
                        enterprises.append(enterprise_info)
                #_logger.debug('#ENTERPRISES::::::::::::::::::::::::::::::::::::::::::::: %s',enterprises)
            
                if enterprises:
                    agency_res = {
                        'id': island['id'],
                        'island': island['name'],
                        'code_island': island['code'],
						'number_enterprise': len(enterprises),
						'enterprises': enterprises
                    }
                    result.append(agency_res)
            result2 = self._prepare_api_response(result, hotelId)
        elif (island_id and hotelId and agency_code!='NONE') or (not island_id and hotelId and agency_code!='NONE'):
            #print "#5:::::::::::::::::::::::::::::::::::::::"
            #_logger.debug('#5:::::::::::::::::::::::::::::::::::::::::::::')

            fares = self.get_fares(checkin_date, checkout_date, enterprise_id=hotelId,agency_code=agency_code)
            if fares:
                #print "IF FARES:::::::::::::::::::::::::::::::::::::::"
                result = self.get_hotel_rooms_list(fares, hotelId,agency_code=agency_code)
                result2 = self._prepare_api_response(result, hotelId)
        elif not island_id and not hotelId and island_code != 'TODAS' and island_code != '' and agency_code=='NONE':
            #print "#6:::::::::::::::::::::::::::::::::::::::"
            #_logger.debug('#6:::::::::::::::::::::::::::::::::::::::::::::')
            result2 = self._prepare_api_response(result, hotelId)
        else:
            _logger.debug('#ELSE:::::::::::::::::::::::::::::::::::::::::::::')

        return result2

    def _prepare_api_response(self, result, hotelId=False):
        response = {'code': '', 'description': '', 'type': ''}

        if result:
            http_status = self.env['http.status'].search([('code','=','200')])
            response = {
                    'code': http_status and http_status.code or '',
                    'description': http_status and http_status.description or '',
                    'type': http_status and http_status.type and http_status.type.name or 'Undefined',
                }
        else:
            http_status = self.env['http.status'].search([('code','=','204')])
            response = {
                    'code': http_status and http_status.code or '',
                    'description': http_status and http_status.description or '',
                    'type': http_status and http_status.type and http_status.type.name or 'Undefined',
                }
        
        if not hotelId or hotelId == 'all':
            response['message'] = {'EnterpriseAvailability': result}
        else:
            response['message'] = result
        return response

    @api.model
    def create_booking(self, data=None):
        #print "CREATE BOOKING ################## ", data
        metadata = {}
        if data and isinstance(data, dict):
            try:
                #print "#1::::::::::::::::::::"
                booking_group_obj = self.env['etourism.booking.group']
                enterprise_id = data.get('enterprise_id', False)
                checkin_date = data.get('arrival_date', False)
                checkout_date = data.get('departure_date', False)
                checkout_date_dur = data.get('departure_date', False)
                source = data.get('source', False)
                agency_code = data.get('agency_code', False)
                client_language = data.get('language', False)
                #print "SOURCE::::::::::::::::::::::::::::::",source
                #print "CLIENT LANGUAGE::::::::::::::::::::::::::::::",client_language
                #print "AGENCY CODE::::::::::::::::::::::::::::::",agency_code
                travel_motive = ''
                partner_id = False                
                prevent_attack = False				
                #search for existing customer otherwise create new customer:
                if 'client' in data and isinstance(data['client'], dict):
                    client = data['client']
                    client_email = client.get('email', False)
                    client_fname = client.get('name', False)
                    client_surname = client.get('surname', False)
                    client_name = ' '.join([str(client_fname), str(client_surname)])
                    client_phone = client.get('telephone', False)
                    client_country = client.get('origin_country', False)
                    travel_motive = client.get('travel_motive', '')
                    customer = self.env['res.partner'].search([('email', '=', client_email)], limit=1)
                    if '.com' in client_fname:
                        prevent_attack = True
                        status_result = 'Your Reservation was considered an Attack attempt'
                        status = 'ERROR'
                    if '.com' in client_surname:
                        prevent_attack = True
                        status_result = 'Your Reservation was considered an Attack attempt'
                        status = 'ERROR'
                    if customer:
                        if '.com' in customer.name:
                            prevent_attack = True
                            status_result = 'Your Reservation was considered an Attack attempt'
                            status = 'ERROR'
                    if not customer and not prevent_attack:
                        customer = self.env['res.partner'].search([('name','=', client_name)])
                    if not customer and not prevent_attack:
                        customer = self.env['res.partner'].create({
                                                        'name': ' '.join([str(client_fname), str(client_surname)]),
                                                        'email': client_email,
                                                        'phone': client_phone,
                                                        'origin': client_country,
                                                    })
                    guest_name, guest_phone, guest_email, guest_country = '', '', '', ''
                    if customer:
                        #print "CUSTOMER ID::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
                        #print customer.id
                        partner_id = customer.id
                        if customer.email != client_email: guest_email = client_email
                        if customer.phone != client_phone: guest_phone = client_phone
                        if customer.origin != client_country: guest_country = client_country
                        if customer.name != client_name: guest_name = client_name

                    #booking details :
                    booking_lines = []
                    flag = False
                    rooms_list = []
                    all_rooms_available = True
                    total_adults, total_children = 0, 0
                    agency_discount = 0.0
	
                    if enterprise_id and checkin_date and checkout_date and partner_id and not prevent_attack:
                        #print "IF ENTERPRISE::::::::::::::::::::::"

                        if 'rooms' in data:
                            #print "IF ROOMS IN DATA::::::::::::::::::::::"
                            room_list = []
                            num_rooms = 0
                            if not data['rooms']:
                                flag = True
                                status_result = 'Missing Rooms details.'
                                status = 'ERROR'                                
                            for line in data['rooms']:
                                print "LINE ##################### ",line
                                pricelist = self.env['product.pricelist.item'].search(
                                    [('id', '=', int(line['item_id']))])
                                #print "FOR LINE IN DATA::::::::::::::::::::::"
                                room_type_id = pricelist.categ_id.id
                                room_id = False                                

                                if agency_code!='NONE':
                                    self._cr.execute("""select pa.discount 
from product_pricelist p, etourism_pricelist_agency pa
where p.id=pa.pricelist_id and p.id=%s and pa.code='%s' limit 1
;"""%(pricelist.pricelist_id.id,agency_code)
                                    )
                                    agency = self._cr.fetchone()
                                    if agency:
                                        agency_discount = agency[0]

                                #get random available Room from Room Type | Avoid creating 2 booking lines with same room
                                if room_type_id:
                                    #print "#2::::::::::::::::::::"
                                    checkin_date = str(checkin_date).replace('/', '-')
                                    checkout_date = str(checkout_date).replace('/', '-')
                                    checkout_date_dur = str(checkout_date_dur).replace('/', '-')
                                    checkin_date = checkin_date.split(' ')[0] + str(' 15:00:00')
                                    checkout_date = checkout_date.split(' ')[0] + str(' 13:00:00')
                                    checkout_date_dur = checkout_date_dur.split(' ')[0] + str(' 15:00:00')
                                    #print "#3::::::::::::::::::::"

                                    duration_vals = (booking_group_obj.onchange_check_dates(checkin_date=checkin_date, checkout_date=checkout_date_dur))
                                    duration = duration_vals.get('duration', 0.0) or data.get('duration', 0.0)
                                    #print "#4::::::::::::::::::::"

                                    no_rooms_required = len(line['distribution']);
                                    for room in line['distribution']:
                                        #print "ROOM ############## ",room
                                        #print "#5::::::::::::::::::::"
                                        if rooms_list:
                                            #print "#6::::::::::::::::::::"
                                            rlist = '(' + ','.join(str(r) for r in rooms_list) + ')'
                                            self._cr.execute("""select v.id from (select id,rooms_availability('{0}','{1}',id) as availability \
                                                                from etourism_room \
                                                                where enterprise_id={2} and room_type_id={3}) v \
                                                                    where v.id not in {4} and v.availability>0""".format(checkin_date, checkout_date, enterprise_id, room_type_id, rlist))
                                        else:
                                            #print "#7::::::::::::::::::::"
                                            self._cr.execute("""select v.id from (select id,rooms_availability('{}','{}',id) as availability \
                                                                from etourism_room \
                                                                where enterprise_id={} and room_type_id={}) v \
                                                                    where v.availability>0""".format(checkin_date, checkout_date, enterprise_id, room_type_id))
                                        room_id = self._cr.fetchone()
                                        #print "#8::::::::::::::::::::"
                                        if room_id:
                                            room_id = room_id[0]
                                        #print "#9::::::::::::::::::::"
                                        if room_id and room_id not in rooms_list:
                                            #print "#9::::::::::::::::::::"
                                            rooms_list.append(room_id)
                                            #check extra beds availability
                                            extra_beds, extra_beds_amount, unitary_amount = 0, 0.0, 0.0
                                            #extra_beds = int(line.get('extra_beds', 0))
                                            item_id = line.get('item_id', 0)
                                            if not pricelist:
                                                #print "#12::::::::::::::::::::"
                                                flag = True
                                                status_result = 'Pricelist Item not found! Id: %s'%(item_id)
                                                status = 'ERROR'
                                                break
                                            else:
                                                #print "#13::::::::::::::::::::"
                                                unitary_amount = pricelist.fixed_price
                                                max_occupancy, max_adults = pricelist[0].max_occupancy, pricelist[0].max_adults
                                                extra_beds = sum(room.get('extra_beds', 0).values())
                                                if max_occupancy >= max_adults:
                                                    #print "#14::::::::::::::::::::"
                                                    allowed_beds = int(max_occupancy - max_adults)
                                                    if extra_beds > allowed_beds:
                                                        status = 'ERROR'
                                                        status_result = 'Requested no. of Beds are not available. Available Beds: %s'%(allowed_beds)
                                                        flag = True
                                                        break
                                                    elif extra_beds <= allowed_beds:
                                                        extra_beds_amount = pricelist[0].additional_price
                                                else:
                                                    #print "#15::::::::::::::::::::"
                                                    status = 'ERROR'
                                                    status_result = 'Requested no. of Beds are not available. Max Occupancy is %s And Included Occupancy is %s'%(max_occupancy, max_adults)
                                                    flag = True
                                                    break
                                            #print "#16::::::::::::::::::::"
                                            booking_condition_id = pricelist[0].booking_condition_id and pricelist[0].booking_condition_id.id or False
                                            extra_beds_amount = sum(room.get('extra_amount', 0).values())
                                            total_amount = (unitary_amount + extra_beds_amount) * duration
                                            if agency_discount > 0:
                                                total_amount = total_amount - (total_amount * (agency_discount / (100 * 1.0)))

                                            #print "#17::::::::::::::::::::"
                                            ids_guests = []
                                            ids_guests.append(partner_id)
                                            #print "ROOM BEFORE BOOKING LINE ############## ", room
                                            booking_line = (0, 0, {
                                                'enterprise_id': enterprise_id,
                                                'checkin': checkin_date,
                                                'checkout': checkout_date,
                                                'enterprise_id_readonly': enterprise_id,
                                                'checkin_readonly': checkin_date,
                                                'checkout_readonly': checkout_date,
                                                'guest_id': partner_id,
                                                'room_id': room_id,
                                                'num_adults': room.get('pax', 0)['adults'],
                                                'num_children': room.get('pax', 0)['children'],
                                                'amount': total_amount,
                                                'discount': agency_discount,
                                                'extra_beds_amount': extra_beds_amount,
                                                'num_extra_bed': extra_beds,
                                                'duration': duration,
                                                'booking_condition_id': booking_condition_id,
                                                'pricelist_item_id': pricelist.id,
                                                'unitary_amount': unitary_amount,
                                                'guest_ids': [(6, 0, ids_guests)],
                                            })
                                            #print "#18::::::::::::::::::::"
                                            booking_lines.append(booking_line)
                                            num_rooms += 1                
                                            total_adults += int(room.get('pax', 0)['adults'])
                                            total_children += int(room.get('pax', 0)['children'])
                                    #print "BOOKING LINES ############# ",booking_lines
                                    #print "#19::::::::::::::::::::"
                                    if len(rooms_list) < no_rooms_required:
                                        all_rooms_available = False
                                    #print "#20::::::::::::::::::::"

                                    if all_rooms_available is False:
                                        status_result = 'Required No of rooms (%s) not found for room type id:%s CheckIn: %s CheckOut: %s'%(no_rooms_required, room_type_id, checkin_date, checkout_date)
                                        status = 'ERROR'
                                        flag = True #indicates error in creating booking lines
                                        break
                                    #print "#21::::::::::::::::::::"

                            #create booking:
                            if flag is False:
                                #print "#22::::::::::::::::::::"
                                booking_group_id = booking_group_obj.create({
                                                            'enterprise_id': enterprise_id,
                                                            'checkin': checkin_date,
                                                            'checkout': checkout_date,
                                                            'guest_id': partner_id,
                                                            'num_rooms': num_rooms,
                                                            'booking_line': booking_lines,
                                                            'duration': duration,
                                                            'num_adults': total_adults,
                                                            'num_children': total_children,
                                                            'origin': source,
                                                            'client_language': client_language,
                                                            'booking_request':False,
                                                            'description': data.get('info', ''),
                                                            'motive': travel_motive,
                                                            'client_name': guest_name,
                                                            'client_email': guest_email,
                                                            'client_phone': guest_phone,
                                                            'client_country': guest_country,
                                    })
                                #print "#23::::::::::::::::::::"
                                booking_group_id.action_pending()
                                #print "#24::::::::::::::::::::"
                                status_result = "Booking registered successfully. Booking Id: %s"%(str(booking_group_id.id))
                                #print "SALE ORDER ID:::::::::::::::::::::::::::::::::::::::::::::::::::"
                                #print booking_group_id.id
                                metadata = {'saleOrderID': booking_group_id.id}
                                status = 'OK'
                                #print "#25::::::::::::::::::::"
                else:
                    #print "CREATE BOOKING :: ELSE #1::::::::::::::::::::"
                    status = 'ERROR'
                    status_result = "Wrong Input Data. Please check booking data. Expected format : {'rooms':[{booking_line_data1},{booking_line_data2}...], 'client':{client_details}, 'enterprise_id':?, 'arrival_date':?, 'departure_date':?, ...}"
            except Exception, e:
                #print "CREATE BOOKING :: EXCEPTION::::::::::::::::::::"
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                status_result = str(e).replace('None', 'False')
                status = 'ERROR '+'line #'+str(exc_tb.tb_lineno)
        else:
            #print "CREATE BOOKING :: ELSE #2::::::::::::::::::::"
            status = 'ERROR'
            status_result = "Wrong Input Data. Please check booking data. Expected format : {'rooms':[{booking_line_data1},{booking_line_data2}...], 'client':{client_details}, 'enterprise_id':?, 'arrival_date':?, 'departure_date':?, ...}"
        return {'status': status, 'comment': status_result, 'metadata':metadata}

    @api.model
    def get_island_locals(self):
        all_locals = self.env['ecom.location'].search([('level','=','5')])
        local_by_islands = {}

        for l in all_locals:
            if l.parent_id:
                parent, level = l, 0
                while parent.level != '2':
                    parent = parent.parent_id

                if parent != l:
                    if parent.name not in local_by_islands:
                        local_by_islands[parent.name] = {'locals': []}
                    else:
                        local_by_islands[parent.name]['locals'].append(l.name)

        return local_by_islands