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

import time
import datetime
from dateutil.relativedelta import relativedelta
import math

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

import urlparse
import uuid

from datetime import date

class ResPartner(models.Model):
    _inherit = ['res.partner']

    @api.one
    @api.depends('birth_date')
    def _get_age(self):
        today = date.today()
        if self.birth_date:
            birth_date = datetime.datetime.strptime(self.birth_date, '%Y-%m-%d').date()
            self.age = str(today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day)))

    current_room = fields.Char(string='Room', compute="_compute_guest_data", search='_search_current_room')
    age = fields.Char(string='Age', compute="_get_age")
    checkin_date = fields.Date(string='Checkin Date', compute="_compute_guest_data")
    checkout_date = fields.Date(string='Checkout Date', compute="_compute_guest_data")
    room_type_name = fields.Char(string='Room Type', compute="_compute_guest_data")
    condition_name = fields.Char(string='Regime', compute="_compute_guest_data")
    client_type = fields.Selection(
        [('guest', 'Particular'),
         ('agency', 'Agency'),
         ('company', 'Company')], string='Type of Client',
        compute='_compute_guest_data')
    company_agency_name = fields.Char(string='Company/Agency', compute="_compute_guest_data", search='_search_agencies_companies')

    @api.one
    def _compute_guest_data(self):
        current_room,checkin,checkout,room_type_name,condition,enterprise_id,client_type,company_agency_name = '', False,False,'','',False,'',''
        for partner in self:
            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
                self._cr.execute("""select distinct r.partner_id as id, t.name as room_name,b.checkin,b.checkout,c.name as room_type_name,cd.name as condition,g.guest_id,par.partner_type,par.name as client_name
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_booking_group g, res_partner par, etourism_room rm,product_product p, product_template t, product_category c, etourism_booking_condition cd 
where r.booking_id=b.id and b.booking_group_id=g.id and g.guest_id=par.id and rm.id=b.room_id and rm.product_id=p.id and p.product_tmpl_id=t.id and rm.room_type_id=c.id and b.booking_condition_id=cd.id
 and r.partner_id=%s and b.enterprise_id=%s and b.state in ('hosted')
"""%(partner.id,enterprise_id.id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        current_room = res[1]
                        checkin = datetime.datetime.strptime(res[2], '%Y-%m-%d %H:%M:%S').date()
                        checkout = datetime.datetime.strptime(res[3], '%Y-%m-%d %H:%M:%S').date()
                        room_type_name = res[4]
                        condition = res[5]
                        client_type = res[7]
                        if client_type in ('agency','company'):
                            company_agency_name = res[8]
                        else:
                            company_agency_name = 'Particular'
            else:
                self._cr.execute("""select distinct r.partner_id as id, t.name as room_name,b.checkin,b.checkout,c.name as room_type_name,cd.name as condition,g.guest_id,par.partner_type,par.name as client_name
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_booking_group g, res_partner par, etourism_room rm,product_product p, product_template t, product_category c, etourism_booking_condition cd 
where r.booking_id=b.id and b.booking_group_id=g.id and g.guest_id=par.id and rm.id=b.room_id and rm.product_id=p.id and p.product_tmpl_id=t.id and rm.room_type_id=c.id and b.booking_condition_id=cd.id
 and r.partner_id=%s and b.state in ('hosted')
"""%(partner.id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        current_room = res[1]
                        checkin = datetime.datetime.strptime(res[2], '%Y-%m-%d %H:%M:%S').date()
                        checkout = datetime.datetime.strptime(res[3], '%Y-%m-%d %H:%M:%S').date()
                        room_type_name = res[4]
                        condition = res[5]
                        client_type = res[7]
                        if client_type in ('agency','company'):
                            company_agency_name = res[8]
                        else:
                            company_agency_name = 'Particular'
			
            partner.current_room = current_room
            partner.checkin_date = checkin
            partner.checkout_date = checkout
            partner.room_type_name = room_type_name
            partner.condition_name = condition
            partner.client_type = client_type
            partner.company_agency_name = company_agency_name

    def _search_current_room(self, operator, value):
        res = []
        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

            self._cr.execute("""select distinct r.partner_id as id, t.name as room_name
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_room rm,product_product p, product_template t 
where r.booking_id=b.id and rm.id=b.room_id and rm.product_id=p.id and p.product_tmpl_id=t.id and lower(t.name)=lower('%s') and b.enterprise_id=%s and b.state in ('hosted')
"""%(value,enterprise_id.id))
            result = self._cr.fetchall()
            for rlt in result:
                res.append(rlt[0])
        else:
            self._cr.execute("""select distinct r.partner_id as id, t.name as room_name
from etourism_booking b,etourism_booking_res_partner_rel r,etourism_room rm,product_product p, product_template t 
where r.booking_id=b.id and rm.id=b.room_id and rm.product_id=p.id and p.product_tmpl_id=t.id and lower(t.name)=lower('%s') and b.state in ('hosted')
"""%(value))
            result = self._cr.fetchall()
            for rlt in result:
                res.append(rlt[0])

        return [('id', 'in', res)]

    def _search_agencies_companies(self, operator, value):
        res = []
        print "OPERATOR:::::::::::::::::",operator
        print "VALUE:::::::::::::::::",value
        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

            self._cr.execute("""select distinct r.partner_id as id,b.checkin,b.checkout,g.guest_id,par.partner_type,par.name as client_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 lower(par.name) like lower('%%%s%%') and b.enterprise_id=%s and b.state in ('hosted')
"""%(value,enterprise_id.id))
            result = self._cr.fetchall()
            for rlt in result:
                res.append(rlt[0])
        else:
            self._cr.execute("""select distinct r.partner_id as id,b.checkin,b.checkout,g.guest_id,par.partner_type,par.name as client_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 lower(par.name) like lower('%%%s%%') and b.state in ('hosted')
"""%(value))
            result = self._cr.fetchall()
            for rlt in result:
                res.append(rlt[0])

        return [('id', 'in', res)]
