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

from odoo import api, fields, models, _


class ReportGuestBySex(models.TransientModel):
    _name = "report.guests.by.sex"

    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise',required=True)
    start_date = fields.Date('Start date')
    end_date = fields.Date('End date')

    @api.model
    def default_get(self, fields):
        res = super(ReportGuestBySex, self).default_get(fields)
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                res.update({'enterprise_id': enterprise_id.id})
        return res

    @api.multi
    def action_print_report(self):
        return self.env['report'].get_action(self, 'etourism_reports.report_guests_by_sex') 

    @api.multi
    def get_guests_info(self, enterprise_id,start_date,end_date,sex):
        result = 0
        if enterprise_id and start_date and end_date and sex:
            domain = [('enterprise_id','=',enterprise_id),('gender', '=', sex),('checkin', '>=', start_date),('checkin', '<=', end_date)]
            result = self.env['view.guests.reports'].search_count(domain)
        return result

    @api.multi
    def get_ebusiness_contacts(self,field=''):
        email,phone,mobile = '','',''
        enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
        ebusiness_id = enterprise_id.ebusiness_id
        for contact in ebusiness_id.contacts_line:
            if contact.default_contact:
                email = contact.email
                phone = contact.phone
                mobile = contact.mobile
        if field == 'email':
            return email
        elif field == 'phone':
            return phone
        elif field == 'mobile':
            return mobile


class ReportGuestByAgeGroup(models.TransientModel):
    _name = "report.guests.by.age.group"

    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise',required=True)
    start_date = fields.Date('Start date')
    end_date = fields.Date('End date')

    @api.model
    def default_get(self, fields):
        res = super(ReportGuestByAgeGroup, self).default_get(fields)
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                res.update({'enterprise_id': enterprise_id.id})
        return res

    @api.multi
    def action_print_report(self):
        return self.env['report'].get_action(self, 'etourism_reports.report_guests_by_age_group') 

    @api.multi
    def get_guests_info(self, enterprise_id,start_date,end_date,min,max):
        result = 0
        if enterprise_id and start_date and end_date and min and max:
            domain = [('enterprise_id','=',enterprise_id),('age', '>', int(min)),('age', '<=', int(max)),('checkin', '>=', start_date),('checkin', '<=', end_date)]
            result = self.env['view.guests.reports'].search_count(domain)
        return result

    @api.multi
    def get_ebusiness_contacts(self,field=''):
        email,phone,mobile = '','',''
        enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
        ebusiness_id = enterprise_id.ebusiness_id
        for contact in ebusiness_id.contacts_line:
            if contact.default_contact:
                email = contact.email
                phone = contact.phone
                mobile = contact.mobile
        if field == 'email':
            return email
        elif field == 'phone':
            return phone
        elif field == 'mobile':
            return mobile


class ReportGuestByCountry(models.TransientModel):
    _name = "report.guests.by.country"

    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise',required=True)
    start_date = fields.Date('Start date')
    end_date = fields.Date('End date')

    @api.model
    def default_get(self, fields):
        res = super(ReportGuestByCountry, self).default_get(fields)
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                res.update({'enterprise_id': enterprise_id.id})
        return res

    @api.multi
    def action_print_report(self):
        return self.env['report'].get_action(self, 'etourism_reports.report_guests_by_country') 

    @api.multi
    def get_guests_info(self, enterprise_id,start_date,end_date):
        result = 0
        if enterprise_id and start_date and end_date and min and max:
            domain = [('enterprise_id','=',enterprise_id),('age', '>', int(min)),('age', '<=', int(max)),('checkin', '>=', start_date),('checkin', '<=', end_date)]
            result = self.env['view.guests.reports'].search_count(domain)
        return result

    @api.multi
    def get_guests_info(self, enterprise_id,start_date,end_date):
        result = []
        return_header = ''
        if enterprise_id and start_date and end_date:
            self._cr.execute("""select c.name as country_name,count(*) as cont from view_guests_reports v, res_country c 
			where c.id=v.country_id and v.enterprise_id=%s and v.checkin >= '%s' and v.checkin <= '%s' and v.country_id is not null group by c.name"""%
                             (enterprise_id,start_date,end_date))
            result = self._cr.fetchall()
            if result:
                for res in result:
                    return_header += """<tr>"""
                    return_header += """<td class="border-top">"""+ str(res[0]) + """</td>"""
                    return_header += """<td class="border-left-top">"""+ str(res[1]) + """</td>"""
                    return_header += """</tr>"""
        return return_header

    @api.multi
    def get_ebusiness_contacts(self,field=''):
        email,phone,mobile = '','',''
        enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
        ebusiness_id = enterprise_id.ebusiness_id
        for contact in ebusiness_id.contacts_line:
            if contact.default_contact:
                email = contact.email
                phone = contact.phone
                mobile = contact.mobile
        if field == 'email':
            return email
        elif field == 'phone':
            return phone
        elif field == 'mobile':
            return mobile


class ReportGuestsForm(models.TransientModel):
    _name = "report.guests.form"
	
    @api.multi
    def action_print_guest_form(self):
        return self.env['report'].get_action(self, 'etourism_reports.report_guests_form') 

    @api.multi
    def get_ebusiness_contacts(self,field=''):
        email,phone,mobile = '','',''
        enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
        ebusiness_id = enterprise_id.ebusiness_id
        for contact in ebusiness_id.contacts_line:
            if contact.default_contact:
                email = contact.email
                phone = contact.phone
                mobile = contact.mobile
        if field == 'email':
            return email
        elif field == 'phone':
            return phone
        elif field == 'mobile':
            return mobile


class ReportCurrentGuests(models.TransientModel):
    _name = "report.current.guests"
	
    @api.multi
    def action_print_current_guests(self):
        return self.env['report'].get_action(self, 'etourism_reports.report_current_guests') 

    @api.multi
    def get_current_guests_info(self):
        result,client_type = [],''
        context = self._context
        return_header = ''
        enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
        count = 0
        if enterprise_id:
            self._cr.execute("""select distinct r.partner_id as id, pr.display_name,t.name as room_name,b.checkin,b.checkout
,c.name as room_type_name,cd.name as condition,par.partner_type,par.name as client_name
from etourism_booking b,etourism_booking_res_partner_rel r,res_partner pr, etourism_room rm,product_product p, product_template t
, product_category c, etourism_booking_condition cd,etourism_booking_group g, res_partner par 
where r.booking_id=b.id and r.partner_id=pr.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 b.booking_group_id=g.id and g.guest_id=par.id
 and b.enterprise_id=%s and b.state in ('hosted')
"""%(enterprise_id.id))
            result = self._cr.fetchall()
            if result:
                for res in result:
                    if count % 2 == 0:
                        return_header += """<tr style="background-color:#FFFFFF;">"""
                    else:
                        return_header += """<tr style="background-color:#F0F0F0;">"""
                    client_type = str(res[7])
                    if client_type == 'guest':
                        client_type = _('Particular')
                    else:
                        client_type = res[8]

                    return_header += """<td>"""+ str(res[1]) + """</td>"""
                    return_header += """<td>"""+ str(client_type) + """</td>"""
                    return_header += """<td>"""+ str(res[2]) + """</td>"""
                    return_header += """<td>"""+ str(res[3])[:10] + """</td>"""
                    return_header += """<td>"""+ str(res[4])[:10] + """</td>"""
                    return_header += """<td>"""+ str(res[5]) + """</td>"""
                    return_header += """<td>"""+ str(res[6]) + """</td>"""
                    return_header += """</tr>"""
                    count += 1
        return return_header

    @api.multi
    def get_current_guests_stats(self,input=''):
        result,num_rooms_enterprise = [],0
        context = self._context
        value,rooms_list,is_all,occupied_rooms = 0,[],False,[]
        enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
        if enterprise_id:
            if input == 'total_guests':
                self._cr.execute("""select count(*)
from etourism_booking b,etourism_booking_res_partner_rel r,res_partner pr, etourism_room rm,product_product p, product_template t
, product_category c, etourism_booking_condition cd 
where r.booking_id=b.id and r.partner_id=pr.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 b.enterprise_id=%s and b.state in ('hosted')
"""%(enterprise_id.id))
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        value += res[0]
            else:
                self._cr.execute("""select count(*) as counter from etourism_room r where r.enterprise_id=%s"""%(enterprise_id.id))
                all_rooms = self._cr.fetchone()
                if all_rooms:
                    num_rooms_enterprise = all_rooms[0]

                self._cr.execute("""select r.id from etourism_room r where r.enterprise_id=%s and r.status='Unvailable'"""%(enterprise_id.id))
                rooms_unavailable = self._cr.fetchall()
                if rooms_unavailable:
                    for room in rooms_unavailable:
                        rooms_list.append(room[0])

                self._cr.execute("""select ss.id,ss.room_type_id from etourism_stop_sales ss 
				where ss.enterprise_id=%s and now() between start_date and end_date"""%(enterprise_id.id))
                stop_sales = self._cr.fetchall()
                if stop_sales:
                    for ss in stop_sales:
                        if not ss[1]:
                            is_all = True
                        else:
                            self._cr.execute("""select r.id from etourism_room r where r.enterprise_id=%s and r.room_type_id=%s"""%(enterprise_id.id,ss[1]))
                            categ_rooms = self._cr.fetchall()
                            if categ_rooms:
                                for ct_room in categ_rooms:
                                    rooms_list.append(ct_room[0])

                if is_all:
                    if input == 'total_rooms_occupied':
                        value = 0
                    elif input == 'total_rooms_unavailable':
                        value = num_rooms_enterprise
                    elif input == 'total_rooms_available':
                        value = 0
                else:
                    rooms_list = list(set(rooms_list))
                    counter = 0
                    self._cr.execute("""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=%s and b.state in ('hosted')"""%(enterprise_id.id))
                    result = self._cr.fetchall()
                    if result:
                        for res in result:
                            occupied_rooms.append(res[0])
                        while counter < len(occupied_rooms):
                            rooms_list = [x for x in rooms_list if x != occupied_rooms[counter]]
                            counter += 1
                    if input == 'total_rooms_occupied':
                        value=len(occupied_rooms)
                    elif input == 'total_rooms_unavailable':
                        value = len(rooms_list)
                    elif input == 'total_rooms_available':
                        value = num_rooms_enterprise - len(occupied_rooms) - len(rooms_list)
        return value

    @api.multi
    def get_ebusiness_contacts(self,field=''):
        email,phone,mobile = '','',''
        enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
        ebusiness_id = enterprise_id.ebusiness_id
        for contact in ebusiness_id.contacts_line:
            if contact.default_contact:
                email = contact.email
                phone = contact.phone
                mobile = contact.mobile
        if field == 'email':
            return email
        elif field == 'phone':
            return phone
        elif field == 'mobile':
            return mobile

