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

from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo import api, fields, models, _
from odoo import tools
import time,calendar,requests
import datetime
from odoo.exceptions import UserError, ValidationError
import urlparse
import json
import logging
_logger = logging.getLogger(__name__)
from odoo.addons.mail.models.mail_template import format_tz

import werkzeug
from urlparse import urljoin

def callFireFunction(url,data):

	r = requests.post(
		url,
            headers={'Content-Type': 'application/json'},
		data=data)
	if r.status_code == 200:
		return r.text
	else:
		raise ValidationError(r.text)

class EventEvent(models.Model):
    _inherit = "event.event"

    #JCF - 06-04-2018
    @api.one
    @api.depends('island_id')
    def _get_island_name(self):
        island_name = ''
        if self.island_id:
            island_name=self.island_id.name
        self.island_name = island_name

    @api.one
    @api.depends('county_id')
    def _get_county_name(self):
        county_name = ''
        if self.county_id:
            county_name=self.county_id.name
        self.county_name = county_name

    @api.one
    @api.depends('island_id')
    def _get_enterprise_island_name(self):
        enterprise_island_name = ''
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            enterprise_island_name=enterprise_id.ebusiness_id.island_id.name
        self.enterprise_island_name = enterprise_island_name

    @api.one
    @api.depends('island_id')
    def _get_advertise_data(self):
        advertise_script = ''
        if self.id:
            advertise_script="""<script>$("#checkme_%s").click(function() {
  $('#button_%s').prop('disabled', function(i, v) { return !v; });
});</script>"""%(self.id,self.id)
        self.advertise_script = advertise_script

    def action_advertise_now(self):
        for event in self:
            if self.env.uid:
                enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
                
                if enterprise_id:
                    event_enterprise = self.env['event.enterprise'].create({
                                                        'event_id': event.id,
                                                        'enterprise_id': enterprise_id.id,
														'origin': 'registration'
														})

        return self.env['warning'].info(title=_('Info!'), message=_('Your request was registered'))

    event_image = fields.Binary('Event image')
    show_dates = fields.Boolean('Show dates',default=False)
    show_location = fields.Boolean('Show location',default=False)
    island_id = fields.Many2one('ecom.location', related="address_id.island_id", string='Island', store=True)
    county_id = fields.Many2one('ecom.location', related="address_id.county_id", string='County', store=True)
    enterprise_line = fields.One2many('event.enterprise', 'event_id', string="Enterprises")
    sequence = fields.Integer(default=1, help="Gives the sequence order when displaying a list of Projects.")
    featured = fields.Boolean(string='Featured',default=False)
    island_name = fields.Char(string='Island Name', compute='_get_island_name', store=True)
    county_name = fields.Char(string='County Name', compute='_get_county_name', store=True)
    num_tourists_expected = fields.Integer(string='Number of Tourists Expected')
    advertise_script = fields.Char(string='Advertise Script', compute='_get_advertise_data', store=True, size=4000)
    is_advertising = fields.Char("Is Advertising on the event", compute="_compute_is_advertising")
    enterprise_island_name = fields.Char(string='Enterprise Island Name', compute='_get_enterprise_island_name')
    event_price = fields.Float(string='Price Event')
    embed_map_src = fields.Text(string='Google Map Embed URL', store=True)

    @api.one
    def _compute_is_advertising(self):
        is_advertising,is_advertising_value = 0,'no'
        # we don't allow public user to see advertising label
        if self.env.user != self.env.ref('base.public_user'):
            enterprise_id = self.env.user.enterprise_id.id
            if enterprise_id:
                for event in self:
                    domain = [('event_id', '=', event.id),('enterprise_id', '=', enterprise_id),('state','in',['open','done'])]
                    is_advertising = self.env['event.enterprise'].search_count(domain)
                if is_advertising > 0:
                    is_advertising_value='yes'
                else:
                    domain = [('event_id', '=', event.id),('enterprise_id', '=', enterprise_id),('state','in',['draft'])]
                    is_advertising = self.env['event.enterprise'].search_count(domain)
                    if is_advertising > 0:
                        is_advertising_value='pending'
                    else:
                        is_advertising_value='no'
            self.is_advertising = is_advertising_value

    @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.multi
    def get_min_amount(self, enterprise_id, date_begin, date_end):
        amount = 0
        if enterprise_id and date_begin and date_end:
            checkin_date = str(date_begin) + str(' 15:00:00')
            checkout_date = str(date_end) + str(' 13:00:00')
            self._cr.execute("""select v2.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.amount limit 1;
                                """ % 
                                (checkin_date, checkout_date, enterprise_id,checkin_date, checkout_date, enterprise_id, enterprise_id, checkin_date)
                            )
            fare = self._cr.fetchone()
            if fare:
                amount = fare[0]

        return amount

    @api.one
    def button_publish(self):
        result,island_name,island_code,enterprise_info,enterprises_info,date_begin_str,date_end_str,event_image = [],'','',{},[],'','',''
        print "########################### PUBLISH EVENT ###########################: "
        if self.featured and self.featured == True:
            print "########################### IF ###########################: "
            if self.island_id:
                island_name = self.island_id.name
                island_code = self.island_id.code
            enterprise_id = False
            min_amount = 0

            if self.date_begin:
                date_begin = datetime.datetime.strptime(self.date_begin, '%Y-%m-%d %H:%M:%S').date()
                date_begin_str = date_begin.strftime('%Y-%m-%d')
            if self.date_end:
                date_end = datetime.datetime.strptime(self.date_end, '%Y-%m-%d %H:%M:%S').date()
                date_end_str = date_end.strftime('%Y-%m-%d')

            if self.event_image:
                event_image = self.get_image_url('event.event', 'event_image', self.id)

            if self.enterprise_line:
                for ent in self.enterprise_line:
                    if ent.state == 'open' or ent.state == 'done':
                        enterprise_id = ent.enterprise_id.id
                        amenities_info, images_count, sold_out = [], 0, False
                        print "ENTERPRISE ID::::::::::::::::::::: ",enterprise_id
                        enterprise_logo = False
                        if enterprise_id:
                            enterprise_logo = self.get_image_url('etourism.enterprise', 'logo', enterprise_id)
                            min_amount = self.get_min_amount(enterprise_id,date_begin_str,date_end_str)

                        if min_amount == 0:
                            sold_out = True

                        if ent.enterprise_id.amenities_ids:
                            for amenity in ent.enterprise_id.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_info.append(amenities_icons)
                                    images_count += 1

                        #print "AMENITIES INFO::::::::::::::::::::::::::::::::::: ",amenities_info

                        enterprise_info = {
							'name': ent.enterprise_id.name,
							'parish': ent.enterprise_id.parish_id.name,
							'local': ent.enterprise_id.local_id.name,
							'NeighBorHood': ent.enterprise_id.neighborhood_id.name,
							'locations': {
								'lat': ent.enterprise_id.latitude,
								'long': ent.enterprise_id.longitude
								},
							'description': {
								'pt': ent.enterprise_id.comment,
								'en': ent.enterprise_id.comment_en,
								'fr': ent.enterprise_id.comment_fr
							},
							'amount': min_amount,
							'soldOut': sold_out,
							'logo': enterprise_logo or '',
							'key': ent.enterprise_id.ebusiness_id.api_key,
							'rating': ent.enterprise_id.rating,
							'amenities': amenities_info
                        }
                        enterprises_info.append(enterprise_info)
            event_res = {
					'eventId': self.id,
					'name': self.name,
					'island': island_name,
					'islandCode': island_code,
					'date': {
					   'begin': date_begin_str,
					   'end': date_end_str
					},
					'eventImage': event_image,
					'hotels': enterprises_info
            }
            result.append(event_res)
            req_hash = callFireFunction(
                "https://us-central1-hotelsgroup-cv-prod.cloudfunctions.net/eTourismEvents",
                json.dumps(event_res)
            )

class EventEnterprise(models.Model):
    _name = 'event.enterprise'
    _description = "Event Enterprises"

    event_id = fields.Many2one('event.event', 'Event', required=True)
    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise', required=True)
    type_id = fields.Many2one('ecom.ebusiness.type', related="enterprise_id.ebusiness_id.ebusiness_type_id", string='Ebusiness Type', store=True)
    country_id = fields.Many2one('ecom.location', related="enterprise_id.ebusiness_id.country_id", string='Country', store=True)
    island_id = fields.Many2one('ecom.location', related="enterprise_id.ebusiness_id.island_id", string='Island', store=True)
    county_id = fields.Many2one('ecom.location', related="enterprise_id.ebusiness_id.county_id", string='County', store=True)
    logo = fields.Binary(string='Logo', related="enterprise_id.logo", track_visibility='onchange', store=True)
    enterprise_state = fields.Selection(string='Enterprise State', related='enterprise_id.ebusiness_state', readonly=True, store=True)
    reservation_no = fields.Char('Reservation No', size=64, readonly=True)
    state = fields.Selection([
        ('draft', 'Unconfirmed'), ('cancel', 'Cancelled'),
        ('open', 'Confirmed'), ('done', 'Done')],
        string='Status', default='draft', readonly=True, copy=False, track_visibility='onchange')
    origin = fields.Selection([
        ('event', 'Event'), ('registration', 'Registration')],
        string='Origin', default='event', readonly=True, copy=False, track_visibility='onchange')

    @api.one
    def do_draft(self):
        self.state = 'draft'

    @api.one
    def confirm_registration(self):
        _logger.info('Sending Email notification on registration confirmation. Event Id: %s'%(self.event_id.id))
        #self.send_email_notification('mail_template_etourism_event_confirmation')

        self.state = 'open'

    @api.one
    def button_reg_cancel(self):
        _logger.info('Sending Email notification on registration cancellation. Event Id: %s'%(self.event_id.id))
        #self.send_email_notification('mail_template_etourism_event_cancellation')
        self.state = 'cancel'

    def get_event_enterprise_emails(self):
        for event in self:
            ebusiness_id = event.enterprise_id.ebusiness_id
            contact_emails = []
            for contact in ebusiness_id.contacts_line:
                if contact.send_email:
                    contact_emails.append(contact.email)
            return ', '.join(contact_emails)

    @api.multi
    def get_current_date(self):
        today_dt_str = ''
        today_dt = datetime.date.today()
        today_dt_str = today_dt.strftime('%d/%m/%Y')
        return today_dt_str

    @api.model
    def create(self, vals):
        print "########################### CREATE EVENT ENTERPRISE ###########################"
        """
        Overrides orm create method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        """
        if not vals:
            vals = {}
        if self._context is None:
            self._context = {}

        vals['reservation_no'] = self.env['ir.sequence'].get('event.enterprise')
        res = super(EventEnterprise, self).create(vals)
        origin = res.origin
        if origin == 'registration':
            _logger.info('Sending Email notification on event registration. Event Id: %s'%(res.event_id.id))
            #res.send_email_notification('mail_template_etourism_event_registration')

        return res

    @api.multi
    def send_email_notification(self, email_template=False):
        print "SEND EVENT EMAIL NOTIFICATION:::::::::::::::::::::::::::::::::"
        if email_template:
            ir_model_data = self.env['ir.model.data']
            try:
                template_id = ir_model_data.get_object_reference('etourism_event', email_template)[1]
            except ValueError:
                template_id = False

            if template_id:
                mail_template = self.env['mail.template']
                template_ids = mail_template.browse(template_id)
                template_ids.with_context({'ltgt_replace': True, 'enterprise_name': self.enterprise_id.name}).send_mail(self.id, force_send=True) 
            else:
                _logger.error('Email template not found. Template: %s Event Id: %s'%(email_template, self.event_id.id))
        return False

class ViewEvents(models.Model):
    _name = 'view.events'
    _auto = False
    _description = "View Events"

    id = fields.Integer('Id')
    name = fields.Char(string='Site',index=True)
    state = fields.Selection([
        ('draft', 'Unconfirmed'), ('cancel', 'Cancelled'),
        ('confirm', 'Confirmed'), ('done', 'Done')],
        string='Status', index=True)
    date_begin = fields.Date(string='Start Date', index=True)
    date_end = fields.Date(string='End Date', index=True)
    featured = fields.Boolean(string='Featured',index=True)
    island_id = fields.Many2one('ecom.location', string='Island id',index=True)
    county_id = fields.Many2one('ecom.location', string='County id',index=True)
    island = fields.Char(string='Island',index=True)
    county = fields.Char(string='County',index=True)

    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'view_events')

        cr.execute("""
CREATE OR REPLACE VIEW view_events AS (		
select e.id,e.name,e.state,e.date_begin::DATE,e.date_end::DATE,e.featured,e.island_id,e.county_id
,l.name as island, l2.name as county
from event_event e, ecom_location l, ecom_location l2
where e.island_id=l.id and e.county_id=l2.id
            )""")
