# -*- 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 odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _

import odoo.addons.decimal_precision as dp
#import mysql.connector
#from mysql.connector import errorcode
import urlparse

class EtourismEnterprise(models.Model):
    _name = 'etourism.enterprise'
    _inherit = ['ir.needaction_mixin', 'mail.thread']
    _description = "Enterprise"

    #JCF - 22-06-2017
    @api.one
    @api.depends('room_line')
    def _get_rooms_data(self):
        if not self.room_line:
            return {}
        res = {}
        number_of_rooms = 0
        for enterprise in self:
            if enterprise.room_line:
                number_of_rooms=len(enterprise.room_line)
        self.num_rooms=number_of_rooms

    #JCF - 22-06-2017
    @api.one
    @api.depends('pricelist_line')
    def _get_pricelist_data(self):
        if not self.pricelist_line:
            return {}
        res = {}
        avg_price = 0.0
        room_price = 0.0
        count = 0
        for enterprise in self:
            if enterprise.pricelist_line:
                for pricelist in enterprise.pricelist_line:
                    room_price = 0.0
                    for item in pricelist.item_ids:
                        count = count + 1
                        room_price=room_price+item.fixed_price
                avg_price=room_price / count
        self.avg_price_rooms=avg_price

    name = fields.Char(string='Name', required=True,index=True)
    ebusiness_id = fields.Many2one('ecom.ebusiness', 'Ebusiness', required=True,index=True)
    type_id = fields.Many2one('ecom.ebusiness.type', related="ebusiness_id.ebusiness_type_id", string='Ebusiness Type', store=True,index=True)
    country_id = fields.Many2one('ecom.location', related="ebusiness_id.country_id", string='Country', store=True,index=True)
    island_id = fields.Many2one('ecom.location', related="ebusiness_id.island_id", string='Island', store=True,index=True)
    county_id = fields.Many2one('ecom.location', related="ebusiness_id.county_id", string='County', store=True,index=True)
    parish_id = fields.Many2one('ecom.location', related="ebusiness_id.parish_id", string='Parish', store=True,index=True)
    customer_id = fields.Many2one('ecom.customer', related="ebusiness_id.customer_id", string='Customer', store=True,index=True)
    logo = fields.Binary('ecom.ebusiness', related="ebusiness_id.logo", track_visibility='onchange', store=True)
    photo = fields.Binary('ecom.ebusiness', related="ebusiness_id.photo", track_visibility='onchange', store=True)
    #Extra tab
    number_stars = fields.Integer('Number of stars')
    number_beds = fields.Integer('Number of beds')
    number_rooms = fields.Integer('Number of rooms')
    extra_bed = fields.Boolean('Provide extra bed?', default=False)
    extra_bed_rate = fields.Float('Extra bed rate')
    #Description tab
    comment = fields.Text(string='Comment', translate=True)
    #Geo-referencing tab
    latitude = fields.Float('Latitude')
    longitude = fields.Float('Longitude')
    altitude = fields.Float('Altitude')
    google_map_url = fields.Char('Google Map URL', size=2000)
    enterprise_id = fields.Char(string='Enterprise ID')
    #Amenities
    amenities_ids = fields.Many2many('etourism.amenities', string='Amenities')
    #Policies
    policies = fields.Text(string='Policies', translate=True)
    enterprise_type_id = fields.Many2one('ecom.ebusiness.type', 'Enterprise type',index=True)
    room_line = fields.One2many('etourism.room', 'enterprise_id', string="Rooms")
    pricelist_line = fields.One2many('product.pricelist', 'enterprise_id', string="Pricelists")
    #JCF 22-06-2017 - Calculated fields
    num_rooms = fields.Integer('Number of rooms (Calc)', compute='_get_rooms_data', store=True)
    avg_price_rooms = fields.Float('Rooms Average Price', compute='_get_pricelist_data', digits=dp.get_precision('Rooms Average Price'), store=True)
    #JCF 14-11-2017 - Calculated fields
    ebusiness_type_code = fields.Char(string='Ebusiness Type Code', related='ebusiness_id.ebusiness_type_id.code', readonly=True, store=True,index=True)
    ebusiness_state = fields.Selection(string='Ebusiness State', related='ebusiness_id.state', readonly=True, store=True,index=True)
    #JCF 06-12-2017 - Rate
    rating = fields.Float('Rating')
    local_id = fields.Many2one('ecom.location', related="ebusiness_id.local_id", string='Local/zone', store=True,index=True)
    neighborhood_id = fields.Many2one('ecom.location', related="ebusiness_id.neighborhood_id", string='Neighborhood', store=True,index=True)
    #JCF 22-02-2018
    policies_en = fields.Text(string='Policies EN')
    comment_en = fields.Text(string='Comment EN')
    #JCF 16-03-2018
    policies_fr = fields.Text(string='Policies FR')
    comment_fr = fields.Text(string='Comment FR')
    #JCF 28-03-2018
    ebusiness_published = fields.Boolean(string='Ebusiness published', related='ebusiness_id.published', readonly=True, store=True,index=True)
    use_reductions = fields.Boolean(string='Use Reductions', default=False)
    #JCF 12-07-2018
    enterprise_image_line = fields.One2many('etourism.enterprise.image', 'enterprise_id','Images')
    #JCF 13-07-2018
    google_maps_iframe = fields.Char('Google maps iframe')

    @api.multi
    def action_update_rating(self):
        self._cr.execute("""update etourism_enterprise t1 set rating = (select count(*) from etourism_booking_group t2 where t2.enterprise_id=t1.id and t2.origin='site') from ecom_ebusiness_type t3 where t1.type_id=t3.id and t3.code='ALO'""")
        print "UPDATE RATINGS:::::::::::::::::::::::::::::::::::::::: "

class EcomEbusiness(models.Model):
    _inherit = 'ecom.ebusiness'

    #JCF - 22-06-2017
    @api.one
    @api.depends('enterprise_line')
    def _get_enterprise_data(self):
        if not self.enterprise_line:
            return {}
        res = {}
        number_of_rooms = 0
        avg_price=0.0
        for ebusiness in self:
            if ebusiness.enterprise_line:
                for enterprise in ebusiness.enterprise_line:
                    number_of_rooms=enterprise.num_rooms
                    avg_price=enterprise.avg_price_rooms
        self.num_rooms=number_of_rooms
        self.avg_price_rooms=avg_price
        self.num_rooms2=number_of_rooms
        self.avg_price_rooms2=avg_price

    sequence_code = fields.Char('Sequence Code')
    enterprise_line = fields.One2many('etourism.enterprise', 'ebusiness_id', string="Enterprises")
    num_rooms = fields.Integer('Number of rooms', compute='_get_enterprise_data', store=True)
    avg_price_rooms = fields.Float('Rooms Average Price', compute='_get_enterprise_data', digits=dp.get_precision('Rooms Average Price'), store=True)
    num_rooms2 = fields.Integer('Number of rooms', compute='_get_enterprise_data', store=True)
    avg_price_rooms2 = fields.Float('Rooms Average Price', compute='_get_enterprise_data', digits=dp.get_precision('Rooms Average Price'), store=True)

    _sql_constraints = [('uniq_sequence_code', 'unique(sequence_code)', 'Sequence Code must be unique for each Ebusiness.')]

    @api.model
    def create(self, vals):

        ebusiness = super(EcomEbusiness, self).create(vals)
        enterprise = self.env['etourism.enterprise'].create({'ebusiness_id': ebusiness.id,'name':vals.get('name')})
        return ebusiness

    @api.multi
    def write(self, vals):
        """
        Overrides orm write method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        update eBusiness history"""
        '''print "WRITE EBUSINESS:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
        print self.id'''
        contracts = []
        enterprise_id=False
        prime_commission,total_amount,percentage=0.0,0.0,0
		
        if 'contract_ebusiness_ids' in vals:
            enterprise = self.env['etourism.enterprise'].search([('ebusiness_id', '=', self.id)], limit=1)
            if enterprise:
                enterprise_id = enterprise.id
            for contract in vals['contract_ebusiness_ids']:
                contracts.append(contract[2])
            contract_ids = self.env['ecom.contract'].search([('id','in',contracts)])
            for cont in contract_ids:
                self._cr.execute("select id,contract_percentage,total_amount from etourism_booking_group  "
                             "where (checkin,checkout) overlaps \
                             ( timestamp %s, timestamp %s ) AND enterprise_id=%s",
                             (cont.start_date, cont.end_date,enterprise_id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        booking_group_id=res[0]
                        percentage=res[1]
                        total_amount=res[2]
                        if total_amount:
                            prime_commission=percentage * total_amount

                        self._cr.execute("""UPDATE etourism_booking_group SET contract_percentage=%s,prime_commission=%s WHERE id=%s"""%(percentage,prime_commission,booking_group_id))
						
        return super(EcomEbusiness, self).write(vals)

    @api.onchange('sequence_code')
    def onchange_sequence_code(self):
        if self.sequence_code:
            self.sequence_code = str(self.sequence_code).upper().strip()


class EtourismEnterpriseTypeView(models.Model):
    _name = 'etourism.enterprise.type.view'
    _description = "Enterprise type view"

    enterprise = fields.Integer(string='Enterprise')
    type = fields.Char(string='Type')
	
    @api.multi
    def action_assign_types(self):
        """Assign types
        """
        enterprise_ids = self.env['etourism.enterprise'].search([('id','>',0)])
        for enterprise in enterprise_ids:
            enterprise_id=enterprise.id
            enterprise=enterprise.enterprise_id
            view_ids = self.env['etourism.enterprise.type.view'].search([('enterprise','=',enterprise)])
            
            for view in view_ids:
                type=view.type
				
                type_ids = self.env['ecom.ebusiness.type'].search([('name','=',type)])
                for enterprise_type in type_ids:
                    id_type=enterprise_type.id

                    self._cr.execute("""UPDATE etourism_enterprise SET enterprise_type_id=%s WHERE id=%s"""%(id_type,enterprise_id))
					
					
class ResPartner(models.Model):
    _inherit = ['res.partner']

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):        
        """ This function filters Guests on Etoursim Booking based on Enterprise
        """
        context = self._context or {}
        print "ENTERPRISE PARTNER NAME SEARCH::::::::::::::::::::::::::::::::"
        print context
        if context and 'filter_enterprise_id' in context and (self.user_has_groups('ecom.group_ecom_hotel') or self.user_has_groups('etourism.group_etourism_directory_tms_operator')):
            guests = []
            if context['filter_enterprise_id']:
                enterprise_id = context['filter_enterprise_id']
                self._cr.execute("""select guest_id from etourism_booking_group where enterprise_id=%s;"""%(enterprise_id)
                            )

                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])

                self._cr.execute("""select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=%s;"""%(enterprise_id)
                            )

                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])

                self._cr.execute("""select p.id from res_partner p where p.is_guest=true 
				and p.id not in (select guest_id from etourism_booking_group where enterprise_id=%s and guest_id is not null)
				and p.id not in (select guest_id from etourism_booking_group where enterprise_id<>%s and guest_id is not null)
				and p.id not in (select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=%s) 
				and p.id not in (select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id<>%s)"""%(enterprise_id,enterprise_id,enterprise_id,enterprise_id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])

                self._cr.execute("""select r.id from res_partner r where r.company_id=%s and r.customer = 't' and r.company_id<>1;"""%(self.env.user.company_id.id))

                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])

                self._cr.execute("""select r.id from res_partner r, res_users u where u.partner_id=r.id""")

                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests = [x for x in guests if x != res[0]]

            guests = list(set(guests))

            #args = [('id','in', guests)]
            args.append((('id','in', guests)))
        if context and 'filter_booking_group_id' in context or 'filter_booking_id' in context:
            guests,booking_group_id,booking_id = [],[],[]
            if 'filter_booking_id' in context and context['filter_booking_id']:
                booking_id = context['filter_booking_id']
                booking_rec = self.env['etourism.booking'].browse(booking_id)
                booking_group_id = booking_rec.booking_group_id.id
            if 'filter_booking_group_id' in context and context['filter_booking_group_id']:
                booking_group_id = context['filter_booking_group_id']
            self._cr.execute("""select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r,etourism_booking_group g where r.booking_id=b.id and b.booking_group_id=g.id and g.id=%s
union all
select g.guest_id from etourism_booking_group g where g.id=%s
				"""%(booking_group_id,booking_group_id))
            result = self._cr.fetchall()
            if result:
                for res in result:
                    guests.append(res[0])
            args.append((('id','in', guests)))

        return super(ResPartner, self).name_search(name, args, operator=operator, limit=limit)	
		
    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        partner_id = False
        if context and 'filter_enterprise_id' in context and (self.user_has_groups('ecom.group_ecom_hotel') or self.user_has_groups('etourism.group_etourism_directory_tms_operator')):
            guests = []
            if context['filter_enterprise_id']:
                enterprise_id = context['filter_enterprise_id']
                self._cr.execute("""select guest_id from etourism_booking_group where enterprise_id=%s;"""%(enterprise_id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])

                self._cr.execute("""select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=%s;"""%(enterprise_id))

                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])
						
                self._cr.execute("""select p.id from res_partner p where p.is_guest=true 
				and p.id not in (select guest_id from etourism_booking_group where enterprise_id=%s and guest_id is not null)
				and p.id not in (select guest_id from etourism_booking_group where enterprise_id<>%s and guest_id is not null)
				and p.id not in (select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=%s)
				and p.id not in (select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id<>%s)"""%(enterprise_id,enterprise_id,enterprise_id,enterprise_id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])

                self._cr.execute("""select r.id from res_partner r where r.company_id=%s and r.customer = 't' and r.company_id<>1;"""%(self.env.user.company_id.id))

                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests.append(res[0])

                self._cr.execute("""select r.id from res_partner r, res_users u where u.partner_id=r.id""")

                result = self._cr.fetchall()
                if result:
                    for res in result:
                        guests = [x for x in guests if x != res[0]]

            guests = list(set(guests))

            args.append((('id','in', guests)))
        else:
            #print "CONTEXT:::::::::::::::::::"
            #print context
            guests = []
            enterprise_id = False
            if self.user_has_groups('ecom.group_ecom_hotel') or self.user_has_groups('etourism.group_etourism_directory_tms_operator'):
                enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
                if context and ('current_guests' in context or 'filter_agencies' in context or 'filter_companies' in context or 'filter_guests' in context):
                    if 'current_guests' in context and 'filter_agencies' not in context and 'filter_companies' not in context and 'filter_guests' not in context:
                        self._cr.execute("""select distinct r.partner_id as id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=%s and b.state in ('hosted')
"""%(enterprise_id.id))
                        result = self._cr.fetchall()
                        if result:
                            for res in result:
                                guests.append(res[0])
                        guests = list(set(guests))
                    else:
                        if 'filter_agencies' in context:
                            self._cr.execute(""" select distinct r.partner_id as id, b.checkin,b.checkout,g.guest_id,par.partner_type,par.name
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_booking_group g, res_partner par
where r.booking_id=b.id and b.booking_group_id=g.id and g.guest_id=par.id
 and b.enterprise_id=%s and b.state in ('hosted') and par.partner_type='agency'
"""%(enterprise_id.id))
                            result = self._cr.fetchall()
                            if result:
                                for res in result:
                                    guests.append(res[0])
                            guests = list(set(guests))

                        if 'filter_companies' in context:
                            self._cr.execute(""" select distinct r.partner_id as id, b.checkin,b.checkout,g.guest_id,par.partner_type,par.name
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_booking_group g, res_partner par
where r.booking_id=b.id and b.booking_group_id=g.id and g.guest_id=par.id
 and b.enterprise_id=%s and b.state in ('hosted') and par.partner_type='company'
"""%(enterprise_id.id))
                            result = self._cr.fetchall()
                            if result:
                                for res in result:
                                    guests.append(res[0])
                            guests = list(set(guests))

                        if 'filter_guests' in context:
                            self._cr.execute(""" select distinct r.partner_id as id, b.checkin,b.checkout,g.guest_id,par.partner_type,par.name
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_booking_group g, res_partner par
where r.booking_id=b.id and b.booking_group_id=g.id and g.guest_id=par.id
 and b.enterprise_id=%s and b.state in ('hosted') and par.partner_type='guest'
"""%(enterprise_id.id))
                            result = self._cr.fetchall()
                            if result:
                                for res in result:
                                    guests.append(res[0])
                            guests = list(set(guests))
                    args.append((('id','in', guests)))

                else:
                    self._cr.execute("""select distinct r.id from res_partner r,etourism_booking_group b where r.id=b.guest_id and b.enterprise_id=%s
union all
select distinct r.partner_id as id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=%s
union all
select distinct p.id from res_partner p where p.is_guest=true 
and p.id not in (select guest_id from etourism_booking_group where enterprise_id=%s and guest_id is not null)
and p.id not in (select guest_id from etourism_booking_group where enterprise_id<>%s and guest_id is not null)
and p.id not in (select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=%s)
and p.id not in (select r.partner_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id<>%s)
union all
select r.id from res_partner r where r.company_id=%s and r.customer = 't' and r.company_id<>1"""%(enterprise_id.id,enterprise_id.id,enterprise_id.id,enterprise_id.id,enterprise_id.id,enterprise_id.id,self.env.user.company_id.id))

                    result = self._cr.fetchall()
                    if result:
                        for res in result:
                            guests.append(res[0])

                    self._cr.execute("""select r.id from res_partner r, res_users u where u.partner_id=r.id""")

                    result = self._cr.fetchall()
                    if result:
                        for res in result:
                            guests = [x for x in guests if x != res[0]]

                    guests = list(set(guests))
                    args.append((('id','in', guests)))
        return super(ResPartner, self).search(args, offset, limit, order, count=count)

class AmenitiesEnterprise(models.Model):
    _name = 'etourism.amenities.etourism.enterprise.rel'
    _description = 'Enterprise Amenities Many2many'
    _table = 'etourism_amenities_etourism_enterprise_rel'
    _rec_name = 'etourism_enterprise_id'

    etourism_enterprise_id = fields.Many2one('etourism.enterprise', string='Enterprise')
    etourism_amenities_id = fields.Many2one('etourism.amenities', string='Amenity')
    featured = fields.Boolean("Featured on Turismo CV", default=False)

class EnterpriseImage(models.Model):
    _name = 'etourism.enterprise.image'
    _description = 'Enterprise Image'

    name = fields.Char(string='Name')
    description = fields.Text(string='Description')
    image_alt = fields.Text(string='Image Label')
    image = fields.Binary(string='Image')
    image_small = fields.Binary(string='Small Image')
    image_url = fields.Char(string='Image URL')
    main_image = fields.Boolean(string='Main Image?', default=False)
    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise',copy=False)

    @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 create(self, vals):

        image = super(EnterpriseImage, self).create(vals)
        image_url = self.get_image_url('etourism.enterprise.image', 'image', image.id)
        image.write({'image_url': image_url})
        return image
		
    @api.multi
    def write(self, vals):
        """
        Overrides orm write method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        """
        vals['image_url'] = self.get_image_url('etourism.enterprise.image', 'image', self.id)

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

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