# -*- coding: utf-8 -*-
###############################################################################
#
#    Tech-Receptives Solutions Pvt. Ltd.
#    Copyright (C) 2009-TODAY Tech-Receptives(<http://www.techreceptives.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _
from odoo import tools

import odoo.addons.decimal_precision as dp

'''class VistaAlojamento(models.Model):
    _name = 'vista.alojamento'
    _auto = False
    _description = "Vista Alojamento"

    id = fields.Integer('Id')
    country_id = fields.Many2one('ecom.location', string='Country id')
    island_id = fields.Many2one('ecom.location', string='Island id')
    county_id = fields.Many2one('ecom.location', string='County id')
    parish_id = fields.Many2one('ecom.location', string='Parish id')
    partner_id = fields.Many2one('res.partner', string='Partner')
    ebusiness_type_id = fields.Many2one('ecom.ebusiness.type', string='Ebusiness type')
    site = fields.Char(string='Site')
    has_contract = fields.Boolean(string='Has contract')
    one_page = fields.Boolean(string='One page')
    type_enterprise = fields.Char(string='Name Type enterprise')
    parent_id = fields.Integer(string='Type parent id')
    id_type_enterprise = fields.Many2one('ecom.ebusiness.type', 'Enterprise type')
    name_type_enterprise = fields.Char(string='Name Enterprise type')
    order_type_enterprise = fields.Integer(string='Order Enterprise type')
    name_ebusiness = fields.Char(string='Fax')
    website = fields.Char(string='Website')
    name_contact = fields.Char(string='Name contact')
    phone_contact = fields.Char(string='Phone contact')
    fax_contact = fields.Char(string='Fax contact')
    street_contact = fields.Char(string='Street contact')
    mobile_contact = fields.Char(string='Mobile contact')
    email_contact = fields.Char(string='Email contact')
    island = fields.Char(string='Island')
    county = fields.Char(string='County')
    parish = fields.Char(string='Parish')
    country = fields.Char(string='Country')
    enterprise_id = fields.Integer('Enterprise id')
    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise')
    longitude = fields.Char(string='Longitude')
    ent_id = fields.Char(string='Ent id')
    latitude = fields.Char(string='Latitude')
    date_online = fields.Integer(string='Date online')
    code_island = fields.Char(string='Code island')
    code_country = fields.Char(string='Code country')
    ordering = fields.Integer(string='Ordering')
    county_ordering = fields.Integer(string='County Ordering')
	
    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'vista_alojamento')

        cr.execute("""
CREATE OR REPLACE VIEW vista_alojamento AS (		
SELECT v.id,
    v.country_id,v.island_id,v.county_id,v.parish_id,v.partner_id,v.ebusiness_type_id,v.site,v.has_contract,v.one_page,v.type_enterprise,v.parent_id,
v.id_type_enterprise,v.name_type_enterprise,v.order_type_enterprise,v.name_ebusiness,v.website,v.name_contact,v.phone_contact,v.fax_contact,v.street_contact
,v.mobile_contact,v.email_contact,v.island,v.county,v.parish,v.country,v.enterprise_id,v.longitude,v.ent_id
,v.latitude,v.date_online
,v.code_island,v.code_country,v.ordering,v.county_ordering
   FROM ( SELECT e.id,e.country_id,e.island_id,e.county_id,e.parish_id,e.partner_id,e.ebusiness_type_id,e.site,e.has_contract,e.one_page,
            te.name AS type_enterprise,te.parent_id,emp.enterprise_type_id AS id_type_enterprise
			,( SELECT ebt.name FROM ecom_ebusiness_type ebt WHERE ebt.id = emp.enterprise_type_id) AS name_type_enterprise
			,( SELECT ebt.ordering FROM ecom_ebusiness_type ebt WHERE ebt.id = emp.enterprise_type_id) AS order_type_enterprise,
            p.name AS name_ebusiness,p.website
			,(select p.name from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as name_contact
			,(select p.email from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as email_contact
			,(select p.phone from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as phone_contact
			,(select p.mobile from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as mobile_contact
			,(select p.fax from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as fax_contact
			,(select p.street from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as street_contact
            ,g.name AS island,
            g.code AS code_island,
            g2.name AS county,
            g3.name AS parish,
            g4.name AS country,
            g4.code AS code_country,
            emp.id AS enterprise_id,
            emp.longitude,
            emp.latitude,
            e.ebusiness_id as ent_id,
            date_online(e.id) AS date_online
            ,g.ordering,g2.ordering as county_ordering
           FROM ecom_ebusiness e
             LEFT JOIN etourism_enterprise emp ON emp.ebusiness_id = e.id
             LEFT JOIN ecom_ebusiness_type te ON e.ebusiness_type_id = te.id
             LEFT JOIN res_partner p ON e.partner_id = p.id
             LEFT JOIN ecom_location g ON e.island_id = g.id
             LEFT JOIN ecom_location g2 ON e.county_id = g2.id
             LEFT JOIN ecom_location g3 ON e.parish_id = g3.id
             LEFT JOIN ecom_location g4 ON e.country_id = g4.id
          WHERE te.id = 111 AND e.published = true 
		  AND g4.code::text = 'CV'::text
		  ) v
  ORDER BY v.ordering,v.island_id, v.county_id, v.order_type_enterprise, v.date_online DESC, v.name_ebusiness
            )""")

class VistaRestauracao(models.Model):
    _name = 'vista.restauracao'
    _auto = False
    _description = "Vista Restauracao"

    id = fields.Integer('Id')
    country_id = fields.Many2one('ecom.location', string='Country id')
    island_id = fields.Many2one('ecom.location', string='Island id')
    county_id = fields.Many2one('ecom.location', string='County id')
    parish_id = fields.Many2one('ecom.location', string='Parish id')
    partner_id = fields.Many2one('res.partner', string='Partner')
    ebusiness_type_id = fields.Many2one('ecom.ebusiness.type', string='Ebusiness type')
    site = fields.Char(string='Site')
    has_contract = fields.Boolean(string='Has contract')
    one_page = fields.Boolean(string='One page')
    type_enterprise = fields.Char(string='Name Type enterprise')
    parent_id = fields.Integer(string='Type parent id')
    id_type_enterprise = fields.Many2one('ecom.ebusiness.type', 'Enterprise type')
    name_type_enterprise = fields.Char(string='Name Enterprise type')
    order_type_enterprise = fields.Integer(string='Order Enterprise type')
    name_ebusiness = fields.Char(string='Fax')
    website = fields.Char(string='Website')
    name_contact = fields.Char(string='Name contact')
    phone_contact = fields.Char(string='Phone contact')
    fax_contact = fields.Char(string='Fax contact')
    street_contact = fields.Char(string='Street contact')
    mobile_contact = fields.Char(string='Mobile contact')
    email_contact = fields.Char(string='Email contact')
    island = fields.Char(string='Island')
    county = fields.Char(string='County')
    parish = fields.Char(string='Parish')
    country = fields.Char(string='Country')
    enterprise_id = fields.Integer('Enterprise id')
    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise')
    longitude = fields.Char(string='Longitude')
    ent_id = fields.Char(string='Ent id')
    latitude = fields.Char(string='Latitude')
    date_online = fields.Integer(string='Date online')
    code_island = fields.Char(string='Code island')
    code_country = fields.Char(string='Code country')
    ordering = fields.Integer(string='Ordering')
    county_ordering = fields.Integer(string='County Ordering')
	
    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'vista_restauracao')

        cr.execute("""
CREATE OR REPLACE VIEW vista_restauracao AS (		
SELECT v.id,
    v.country_id,v.island_id,v.county_id,v.parish_id,v.partner_id,v.ebusiness_type_id,v.site,v.has_contract,v.one_page,v.type_enterprise,v.parent_id,
v.id_type_enterprise,v.name_type_enterprise,v.order_type_enterprise,v.name_ebusiness,v.website,v.name_contact,v.phone_contact,v.fax_contact,v.street_contact
,v.mobile_contact,v.email_contact,v.island,v.county,v.parish,v.country,v.enterprise_id,v.longitude,v.ent_id
,v.latitude,v.date_online
,v.code_island,v.code_country,v.ordering,v.county_ordering
   FROM ( SELECT e.id,e.country_id,e.island_id,e.county_id,e.parish_id,e.partner_id,e.ebusiness_type_id,e.site,e.has_contract,e.one_page,
            te.name AS type_enterprise,te.parent_id,emp.enterprise_type_id AS id_type_enterprise
			,( SELECT ebt.name FROM ecom_ebusiness_type ebt WHERE ebt.id = emp.enterprise_type_id) AS name_type_enterprise
			,( SELECT ebt.ordering FROM ecom_ebusiness_type ebt WHERE ebt.id = emp.enterprise_type_id) AS order_type_enterprise,
            p.name AS name_ebusiness,p.website
			,(select p.name from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as name_contact
			,(select p.email from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as email_contact
			,(select p.phone from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as phone_contact
			,(select p.mobile from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as mobile_contact
			,(select p.fax from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as fax_contact
			,(select p.street from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as street_contact
            ,g.name AS island,
            g.code AS code_island,
            g2.name AS county,
            g3.name AS parish,
            g4.name AS country,
            g4.code AS code_country,
            emp.id AS enterprise_id,
            emp.longitude,
            emp.latitude,
            e.ebusiness_id as ent_id,
            date_online(e.id) AS date_online
            ,g.ordering,g2.ordering as county_ordering
           FROM ecom_ebusiness e
             LEFT JOIN etourism_enterprise emp ON emp.ebusiness_id = e.id
             LEFT JOIN ecom_ebusiness_type te ON e.ebusiness_type_id = te.id
             LEFT JOIN res_partner p ON e.partner_id = p.id
             LEFT JOIN ecom_location g ON e.island_id = g.id
             LEFT JOIN ecom_location g2 ON e.county_id = g2.id
             LEFT JOIN ecom_location g3 ON e.parish_id = g3.id
             LEFT JOIN ecom_location g4 ON e.country_id = g4.id
          WHERE te.id = 121 AND e.published = true 
		  AND g4.code::text = 'CV'::text
		  ) v
  ORDER BY v.ordering,v.island_id, v.county_id, v.order_type_enterprise, v.date_online DESC, v.name_ebusiness
            )""")

class VistaIntermediacao(models.Model):
    _name = 'vista.intermediacao'
    _auto = False
    _description = "Vista Intermediacao"

    id = fields.Integer('Id')
    country_id = fields.Many2one('ecom.location', string='Country id')
    island_id = fields.Many2one('ecom.location', string='Island id')
    county_id = fields.Many2one('ecom.location', string='County id')
    parish_id = fields.Many2one('ecom.location', string='Parish id')
    partner_id = fields.Many2one('res.partner', string='Partner')
    ebusiness_type_id = fields.Many2one('ecom.ebusiness.type', string='Ebusiness type')
    site = fields.Char(string='Site')
    has_contract = fields.Boolean(string='Has contract')
    one_page = fields.Boolean(string='One page')
    type_enterprise = fields.Char(string='Name Type enterprise')
    parent_id = fields.Integer(string='Type parent id')
    id_type_enterprise = fields.Many2one('ecom.ebusiness.type', 'Enterprise type')
    name_type_enterprise = fields.Char(string='Name Enterprise type')
    order_type_enterprise = fields.Integer(string='Order Enterprise type')
    name_ebusiness = fields.Char(string='Fax')
    website = fields.Char(string='Website')
    name_contact = fields.Char(string='Name contact')
    phone_contact = fields.Char(string='Phone contact')
    fax_contact = fields.Char(string='Fax contact')
    street_contact = fields.Char(string='Street contact')
    mobile_contact = fields.Char(string='Mobile contact')
    email_contact = fields.Char(string='Email contact')
    island = fields.Char(string='Island')
    county = fields.Char(string='County')
    parish = fields.Char(string='Parish')
    country = fields.Char(string='Country')
    enterprise_id = fields.Integer('Enterprise id')
    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise')
    longitude = fields.Char(string='Longitude')
    ent_id = fields.Char(string='Ent id')
    latitude = fields.Char(string='Latitude')
    date_online = fields.Integer(string='Date online')
    code_island = fields.Char(string='Code island')
    code_country = fields.Char(string='Code country')
    ordering = fields.Integer(string='Ordering')
    county_ordering = fields.Integer(string='County Ordering')
	
    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'vista_intermediacao')

        cr.execute("""
CREATE OR REPLACE VIEW vista_intermediacao AS (		
SELECT v.id,
    v.country_id,v.island_id,v.county_id,v.parish_id,v.partner_id,v.ebusiness_type_id,v.site,v.has_contract,v.one_page,v.type_enterprise,v.parent_id,
v.id_type_enterprise,v.name_type_enterprise,v.order_type_enterprise,v.name_ebusiness,v.website,v.name_contact,v.phone_contact,v.fax_contact,v.street_contact
,v.mobile_contact,v.email_contact,v.island,v.county,v.parish,v.country,v.enterprise_id,v.longitude,v.ent_id
,v.latitude,v.date_online
,v.code_island,v.code_country,v.ordering,v.county_ordering
   FROM ( SELECT e.id,e.country_id,e.island_id,e.county_id,e.parish_id,e.partner_id,e.ebusiness_type_id,e.site,e.has_contract,e.one_page,
            te.name AS type_enterprise,te.parent_id,emp.enterprise_type_id AS id_type_enterprise
			,( SELECT ebt.name FROM ecom_ebusiness_type ebt WHERE ebt.id = emp.enterprise_type_id) AS name_type_enterprise
			,( SELECT ebt.ordering FROM ecom_ebusiness_type ebt WHERE ebt.id = emp.enterprise_type_id) AS order_type_enterprise,
            p.name AS name_ebusiness,p.website
			,(select p.name from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as name_contact
			,(select p.email from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as email_contact
			,(select p.phone from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as phone_contact
			,(select p.mobile from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as mobile_contact
			,(select p.fax from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as fax_contact
			,(select p.street from res_partner p,ecom_ebusiness_contact_rel c where p.id=c.contact_id and c.ebusiness_id=e.id and p.default_contact is true) as street_contact
            ,g.name AS island,
            g.code AS code_island,
            g2.name AS county,
            g3.name AS parish,
            g4.name AS country,
            g4.code AS code_country,
            emp.id AS enterprise_id,
            emp.longitude,
            emp.latitude,
            e.ebusiness_id as ent_id,
            date_online(e.id) AS date_online
            ,g.ordering,g2.ordering as county_ordering
           FROM ecom_ebusiness e
             LEFT JOIN etourism_enterprise emp ON emp.ebusiness_id = e.id
             LEFT JOIN ecom_ebusiness_type te ON e.ebusiness_type_id = te.id
             LEFT JOIN res_partner p ON e.partner_id = p.id
             LEFT JOIN ecom_location g ON e.island_id = g.id
             LEFT JOIN ecom_location g2 ON e.county_id = g2.id
             LEFT JOIN ecom_location g3 ON e.parish_id = g3.id
             LEFT JOIN ecom_location g4 ON e.country_id = g4.id
          WHERE te.id = 126 AND e.published = true 
		  AND g4.code::text = 'CV'::text
		  ) v
  ORDER BY v.ordering,v.island_id, v.county_id, v.order_type_enterprise, v.date_online DESC, v.name_ebusiness
            )""")'''
			
class ViewEnterprises(models.Model):
    _name = 'view.enterprises'
    _auto = False
    _description = "View Enterprises"

    id = fields.Integer('Id')
    country_id = fields.Many2one('ecom.location', string='Country id',index=True)
    island_id = fields.Many2one('ecom.location', string='Island id',index=True)
    county_id = fields.Many2one('ecom.location', string='County id',index=True)
    parish_id = fields.Many2one('ecom.location', string='Parish id',index=True)
    partner_id = fields.Many2one('res.partner', string='Partner',index=True)
    type_id = fields.Many2one('ecom.ebusiness.type', string='Ebusiness type',index=True)
    enterprise_type_id = fields.Many2one('ecom.ebusiness.type', string='Enterprise type',index=True)
    site = fields.Char(string='Site')
    ebusiness_id = fields.Many2one('ecom.ebusiness', string='Ebusiness',index=True)
    name_type_ebusiness = fields.Char(string='Name type ebusiness')
    name_type_enterprise = fields.Char(string='Name type enterprise')
    name_enterprise = fields.Char(string='Name Enterprise')
    comment = fields.Text(string='Description')
    phone = fields.Char(string='Phone contact')
    mobile = fields.Char(string='Fax contact')
    email = fields.Char(string='Street contact')
    nif = fields.Char(string='Mobile contact')
    island = fields.Char(string='Island')
    county = fields.Char(string='County')
    parish = fields.Char(string='Parish')
    captcha_key = fields.Char(string='Captcha Key')
    api_key = fields.Char(string='API Key')
    policies = fields.Text(string='Policies')
    #JCF 06-12-2017 - Rate
    rating = fields.Float('Rating')
    local_id = fields.Many2one('ecom.location', string='Local id',index=True)
    local = fields.Char(string='Local')
    neighborhood_id = fields.Many2one('ecom.location', string='Neighborhood id',index=True)
    neighborhood = fields.Char(string='Neighborhood')
    #JCF - 09-02-2018
    our_site = fields.Boolean('Our site')
    #JCF 22-02-2018
    policies_en = fields.Text(string='Policies EN')
    comment_en = fields.Text(string='Comment EN')
    #JCF 02-03-2018
    latitude = fields.Float('Latitude')
    longitude = fields.Float('Longitude')
    #JCF 08-03-2018
    featured = fields.Integer('Featured',index=True)
    #JCF 26-03-2018
    code_island = fields.Char('Code Island',index=True)
    code_county = fields.Char(string='Code county',index=True)
    #JCF 27-03-2018
    policies_fr = fields.Text(string='Policies FR')
    comment_fr = fields.Text(string='Comment FR')
    #JCF 20-04-2018
    use_reductions = fields.Boolean(string='Use Reductions',index=True)

    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'view_enterprises')

        cr.execute("""
CREATE OR REPLACE VIEW view_enterprises AS (		
SELECT e.id, e.country_id, e.island_id, e.county_id, e.parish_id, eb.partner_id, e.type_id,e.enterprise_type_id,eb.site 
,eb.id AS ebusiness_id
,te.name AS name_type_ebusiness,te2.name as name_type_enterprise
, e.name AS name_enterprise,e.comment
, ct.phone,ct.mobile, ct.email, ct.nif
, l.name AS island, l2.name AS county, l3.name AS parish,eb.captcha_key,eb.api_key,e.policies,e.rating,e.local_id,l4.name as local,e.neighborhood_id
,l5.name as neighborhood,eb.our_site,e.comment_en,e.policies_en,e.latitude,e.longitude,eb.featured,l.code as code_island,l2.code as code_county,e.comment_fr,e.policies_fr,e.use_reductions
   FROM etourism_enterprise e
   LEFT JOIN ecom_ebusiness_type te ON e.type_id = te.id
   LEFT JOIN ecom_ebusiness_type te2 ON e.enterprise_type_id = te2.id
   LEFT JOIN ecom_ebusiness eb ON e.ebusiness_id = eb.id
   LEFT JOIN res_partner p ON eb.partner_id = p.id
   LEFT JOIN ecom_ebusiness_contact ct ON (ct.ebusiness_id = eb.id and ct.default_contact is true)
   LEFT JOIN ecom_location l ON e.island_id = l.id
   LEFT JOIN ecom_location l2 ON e.county_id = l2.id
   LEFT JOIN ecom_location l3 ON e.parish_id = l3.id
   LEFT JOIN ecom_location l4 ON e.local_id = l4.id
   LEFT JOIN ecom_location l5 ON e.neighborhood_id = l5.id
  WHERE te.code = 'ALO' and eb.published is true
            )""")

class ViewFares(models.Model):
    _name = 'view.fares'
    _auto = False
    _description = "View Fares"

    id = fields.Integer('Id')
    enterprise_id = fields.Many2one('etourism.enterprise', string='ID Enterprise',index=True)
    name_enterprise = fields.Char(string='Name Enterprise')
    country_id = fields.Many2one('ecom.location', string='Country id',index=True)
    island_id = fields.Many2one('ecom.location', string='Island id',index=True)
    county_id = fields.Many2one('ecom.location', string='County id',index=True)
    parish_id = fields.Many2one('ecom.location', string='Parish id',index=True)
    island = fields.Char(string='Island')
    county = fields.Char(string='County')
    parish = fields.Char(string='Parish')
    site = fields.Char(string='Site')
    ebusiness_id = fields.Many2one('ecom.ebusiness', string='Ebusiness',index=True)
    room_type_id = fields.Many2one('product.category', string='Room type',index=True)
    name_room_type = fields.Char(string='Name room type')
    condition_id = fields.Many2one('etourism.booking.condition', string='Booking condition',index=True)
    name_condition = fields.Char(string='Name condition')
    price_item_id = fields.Many2one('product.pricelist.item', string='Pricelist item',index=True)
    #name_price_item = fields.Char(string='Name price item')
    amount = fields.Float(string='Amount')
    max_adults = fields.Float(string='Max adults')
    max_children = fields.Float(string='Max children')
    max_occupancy = fields.Integer(string='Maximum Occupancy')
    additional_price = fields.Float('Additional Price', digits=dp.get_precision('Additional Price'))
    num_adults = fields.Float(string='Num adults')
    comment = fields.Text(string='Description')
    type_id = fields.Many2one('ecom.ebusiness.type', string='Ebusiness type',index=True)
    enterprise_type_id = fields.Many2one('ecom.ebusiness.type', string='Enterprise type',index=True)
    name_type_ebusiness = fields.Char(string='Name type ebusiness')
    name_type_enterprise = fields.Char(string='Name type enterprise')
    start_date = fields.Date(string='Start date')
    end_date = fields.Date(string='End date')
    publish_online = fields.Boolean(string='Publish Online')
    policies = fields.Text(string='Policies')
    api_key = fields.Char(string='API Key')
    #JCF 06-12-2017 - Rate
    rating = fields.Float('Rating')
    local_id = fields.Many2one('ecom.location', string='Local id',index=True)
    local = fields.Char(string='Local/Zone')
    neighborhood_id = fields.Many2one('ecom.location', string='Neighborhood id',index=True)
    neighborhood = fields.Char(string='Neighborhood')
    #JCF - 09-02-2018
    our_site = fields.Boolean('Our site')
    #JCF 22-02-2018
    policies_en = fields.Text(string='Policies EN')
    comment_en = fields.Text(string='Comment EN')
    #JCF 02-03-2018
    latitude = fields.Float('Latitude')
    longitude = fields.Float('Longitude')
    #JCF 08-03-2018
    featured = fields.Integer('Featured',index=True)
    #JCF 26-03-2018
    code_island = fields.Char('Code Island',index=True)
    code_county = fields.Char(string='Code county',index=True)
    #JCF 27-03-2018
    policies_fr = fields.Text(string='Policies FR')
    comment_fr = fields.Text(string='Comment FR')
    #JCF 05-04-2018
    currency_symbol = fields.Char('Currency Symbol',index=True)
    #JCF 20-04-2018
    use_reductions = fields.Boolean(string='Use Reductions',index=True)
    pricelist_id = fields.Many2one('product.pricelist', string='Pricelist id',index=True)

    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'view_fares')
        cr.execute("""
CREATE OR REPLACE VIEW view_fares AS (		
SELECT i.id,e.id as enterprise_id, e.name_enterprise, e.country_id, e.island_id, e.county_id, e.parish_id
,e.island, e.county, e.parish, e.site, e.ebusiness_id, pc.id AS room_type_id
 , pc.name AS name_room_type, c.id AS condition_id, c.name AS name_condition,i.id AS price_item_id
 , i.fixed_price AS amount,i.max_adults,i.max_children,i.max_occupancy,i.additional_price, pc.num_adults, e.comment, e.type_id,e.enterprise_type_id
 , e.name_type_ebusiness,e.name_type_enterprise, p.start_date, p.end_date, p.publish_online,e.policies,e.api_key,e.rating, e.local_id,e.local
 ,e.neighborhood_id,e.neighborhood,e.our_site,e.comment_en,e.policies_en,e.latitude,e.longitude,e.featured,e.code_island,e.code_county
 ,e.comment_fr,e.policies_fr,cur.symbol as currency_symbol,e.use_reductions,i.pricelist_id
   FROM product_pricelist_item i
   LEFT JOIN etourism_booking_condition c ON c.id = i.booking_condition_id
   LEFT JOIN product_category pc ON pc.id = i.categ_id
   LEFT JOIN product_pricelist p ON p.id = i.pricelist_id
   LEFT JOIN view_enterprises e ON e.id = i.enterprise_id
   LEFT JOIN res_currency cur ON cur.id = i.currency_id
WHERE p.publish_online is true and p.online_pricelist is true
            )""")

        tools.drop_view_if_exists(cr, 'view_rooms')

        cr.execute("""
CREATE OR REPLACE VIEW view_rooms AS (		
 SELECT r.id,
    r.status,
    r.product_id,
    r.enterprise_id,
    p.product_tmpl_id,
    p.isroom,
    t.list_price,
    t.name AS room_name,
    t.categ_id,
    c.name AS name_type_room,
    c.num_adults,
	c.num_children,
	c.num_rooms
   FROM etourism_room r
     LEFT JOIN product_product p ON p.id = r.product_id
     LEFT JOIN product_template t ON t.id = p.product_tmpl_id
     LEFT JOIN product_category c ON t.categ_id = c.id
	 )""")
	 
        cr.execute("""
CREATE OR REPLACE FUNCTION rooms_availability(timestamp with time zone, timestamp with time zone, integer)
  RETURNS integer AS
$BODY$ declare
	v_return integer;
	v_booking RECORD ;
	v_room_id integer:=0; 
	v_counter integer:=0; 
	v_booking_state varchar;
	v_tmp integer:=0;

	v_estado varchar;
 begin

	select status into v_booking_state from etourism_room r where r.id=$3;
	
	FOR v_booking IN SELECT room_id,checkin,checkout,state FROM etourism_booking where (checkin,checkout) overlaps ( $1,$2 ) and room_id=$3 and state in ('request','confirmed','pending','hosted','checkout') LOOP
		
		v_counter:=v_counter+1;
	end loop;       

	if v_counter = 0 and v_booking_state <> 'Unvailable'
	then
		v_return:=1;
	else
		v_return:=0;
	end if;
	
         return v_return;
 end;$BODY$
  LANGUAGE plpgsql VOLATILE
            """)


        cr.execute("""
CREATE OR REPLACE FUNCTION rooms_availability_no_limit(timestamp with time zone, timestamp with time zone, integer, integer)
  RETURNS integer AS
$BODY$ declare
	v_return integer:=0;
	v_room RECORD ;         
	v_room2 RECORD ;         
	v_room3 RECORD ;         
	v_room_id integer:=0; 
	v_availability integer:=0;
	v_counter integer:=0; 
begin

		FOR v_room IN select v.id from view_rooms v where v.enterprise_id=$3 and v.categ_id=$4 order by v.id LOOP
			v_room_id:=v_room.id;	
		
			select rooms_availability($1,$2,v_room_id) into v_availability from view_rooms where id=v_room_id;

			if v_availability > 0
			then
				v_return:=v_return + 1; 
			else
				v_return:=v_return; 
			end if;
		END LOOP;

		FOR v_room2 IN select count(*) as counter from etourism_stop_sales ss where ss.enterprise_id=$3 and (start_date,end_date) overlaps ($1,$2) and ss.room_type_id=$4 LOOP
			v_counter:=v_room2.counter;	
		
		END LOOP;

		FOR v_room3 IN select count(*) as counter from etourism_stop_sales ss where ss.enterprise_id=$3 and (start_date,end_date) overlaps ($1,$2) and ss.room_type_id is null LOOP
			v_counter:=v_counter + v_room3.counter;
		END LOOP;

		IF v_counter > 0 
		THEN
			v_return:=0;
		ELSE
			v_return:=v_return; 
		END IF;

        return v_return;
 end;$BODY$
  LANGUAGE plpgsql VOLATILE
            """)
		
        cr.execute("""
CREATE OR REPLACE FUNCTION rooms_availability_by_categ(timestamp with time zone, timestamp with time zone, integer, integer)
  RETURNS integer AS
$BODY$ declare
	v_return integer:=0;
	v_room RECORD ;         
	v_room2 RECORD ;         
	v_room3 RECORD ;         
	v_counter integer:=0; 
	v_counter2 integer:=0; 
	v_availability integer:=0;
begin

	FOR v_room IN select count(*) as counter from (select q.*,rooms_availability($1,$2,q.id) as availability 
from view_rooms q) q2 where q2.availability = 1 and q2.enterprise_id=$3 and q2.categ_id=$4 LOOP
		v_counter:=v_room.counter;	
	
	END LOOP;

	FOR v_room2 IN select count(*) as counter from etourism_stop_sales ss where ss.enterprise_id=$3 and (start_date,end_date) overlaps ($1,$2) and ss.room_type_id=$4 LOOP
		v_counter2:=v_room2.counter;	
	
	END LOOP;

	FOR v_room3 IN select count(*) as counter from etourism_stop_sales ss where ss.enterprise_id=$3 and (start_date,end_date) overlaps ($1,$2) and ss.room_type_id is null LOOP
		v_counter2:=v_counter2 + v_room3.counter;
	END LOOP;

	IF v_counter2 > 0 
	THEN
		v_return:=0;
	ELSE
		v_return:=v_counter;
	END IF;

    return v_return;
 end;$BODY$
  LANGUAGE plpgsql VOLATILE            """)
  
 
        cr.execute("""
CREATE OR REPLACE FUNCTION room_current_availability(integer, integer,integer)
  RETURNS integer AS
$BODY$ declare
	v_return integer;
	v_booking RECORD ;
	v_stop_sales RECORD ;
	v_stop_sales2 RECORD ;
	v_room_id integer:=0; 
	v_counter integer:=0; 
	v_booking_state varchar;
	v_tmp integer:=0;

	v_estado varchar;
 begin

	select status into v_booking_state from etourism_room r where r.id=$1;

	if v_booking_state = 'Unvailable'
	then
		v_counter:=v_counter+1;
	end if;
	
	FOR v_booking IN SELECT room_id,checkin,checkout,state FROM etourism_booking where now() between checkin and checkout and room_id=$1 and state in ('request','confirmed','pending','hosted','checkout') LOOP
		
		v_counter:=v_counter+1;
	end loop;       

	FOR v_stop_sales IN select count(*) as counter from etourism_stop_sales ss where ss.enterprise_id=$3 and now() between start_date and end_date and ss.room_type_id=$2 LOOP
		v_counter:=v_counter+ v_stop_sales.counter;	
	
	END LOOP;

	FOR v_stop_sales2 IN select count(*) as counter from etourism_stop_sales ss where ss.enterprise_id=$3 and now() between start_date and end_date and ss.room_type_id is null LOOP
		v_counter:=v_counter + v_stop_sales2.counter;
	END LOOP;

	IF v_counter > 0 
	THEN
		v_return:=0;
	ELSE
		v_return:=1; 
	END IF;

        return v_return;
 end;$BODY$
  LANGUAGE plpgsql VOLATILE
""")

        cr.execute("""
CREATE OR REPLACE FUNCTION get_num_rooms_available_occupied(integer, varchar)
  RETURNS integer AS
$BODY$ declare
	v_return integer;
 begin

	IF $2 = 'total_rooms_occupied'
	THEN
		select count(*) into v_return from (select distinct b.room_id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=$1 and b.state in ('hosted')) v;
	END IF;

	IF $2 = 'total_rooms_available'
	THEN
		select count(*) into v_return from etourism_room r where r.id not in (select distinct b.room_id as id from etourism_booking b,etourism_booking_res_partner_rel r where r.booking_id=b.id and b.enterprise_id=$1 and b.state in ('hosted')) and r.enterprise_id=$1;
	END IF;

	IF $2 = 'total_rooms_unavailable'
	THEN
		select count(*) into v_return from etourism_room r where status = 'Unvailable' and r.enterprise_id=$1;
	END IF;

    return v_return;
 end;$BODY$
  LANGUAGE plpgsql VOLATILE
""")

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

class ViewRoomStatus(models.Model):
    _name = 'view.rooms.status'
    _auto = False
    _description = "Vista estado dos quartos"

    id = fields.Integer(string='Id')
    room_id = fields.Many2one('etourism.room', 'Room', required=True)
    enterprise_id = fields.Many2one('etourism.enterprise', string='ID Enterprise', index=True)
    room_type_id = fields.Many2one('product.category', string='Room type',index=True)
    status = fields.Selection([('Available', 'Available'),
                               ('Unvailable', 'Unavailable'),
                               ], 'Status', default='Available', track_visibility='onchange')
    unavailable_start_date = fields.Date(string='Unavailable Start date')
    unavailable_end_date = fields.Date(string='Unavailable End date')
    stop_sale_start_date = fields.Date(string='Stop Sale Start date')
    stop_sale_end_date = fields.Date(string='Stop Sale End date')

    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'view_rooms_status')
        cr.execute("""
            CREATE OR REPLACE VIEW view_rooms_status AS (
                select row_number() OVER (ORDER BY room_id) AS id,* from (select r.id as room_id,
                    r.enterprise_id,
                    pt.name,
                    r.room_type_id,
                    r.status,
                    r.start_date unavailable_start_date,
                    r.end_date unavailable_end_date,
                    ss.start_date as stop_sale_start_date,
                    ss.end_date as stop_sale_end_date
                    from etourism_room as r
                    left join etourism_stop_sales as ss ON (ss.room_type_id=r.room_type_id and ss.enterprise_id=r.enterprise_id)
                    left join product_product p ON (r.product_id=p.id)
                    left join product_template pt ON (p.product_tmpl_id=pt.id)
                    ORDER BY ss.enterprise_id,r.room_type_id) v
                    where v.status = 'Unvailable' or (v.status='Available' and v.stop_sale_start_date is not null)
            )"""
        );
