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

from odoo import models, fields, api, _
import logging
_logger = logging.getLogger(__name__)

from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
from odoo.tools.misc import formatLang
from datetime import datetime
from odoo.addons.mail.models.mail_template import format_tz
from odoo.exceptions import UserError, ValidationError

import werkzeug
from urlparse import urljoin

class Booking(models.Model):
    _inherit = "etourism.booking.group"

    @api.model
    def create(self, vals):
        booking = super(Booking, self).create(vals)
        booking_id = booking.id
        print "CREATE MAIL NOTIFICATION BOOKING GROUP: ", vals

        if booking.origin=='site' or booking.origin=='tourism' or booking.origin=='agency':
            _logger.info('Sending Email notification on new booking registration. Booking Id: %s'%(booking_id))
            booking.sudo().send_email_notification('mail_template_etourism_booking_registration')

            _logger.info('Sending Email notification on new booking registration (Hotel Copy). Booking Id: %s'%(booking_id))
            booking.sudo().send_email_notification('mail_template_etourism_booking_registration_hotel_copy')
        if booking.origin=='agency':
            _logger.info('Sending Email notification on new booking registration to the Agency. Booking Id: %s'%(booking_id))
            booking.sudo().send_email_notification('mail_template_etourism_booking_registration_agency')
        if booking.origin=='pms':
            _logger.info('Sending Email notification on new booking confirmation to the customer. Booking Id: %s'%(booking_id))
            booking.sudo().send_email_notification('mail_template_etourism_booking_confirmation')
        return booking

    @api.multi
    def write(self, vals):
        res = super(Booking, self).write(vals)
        #print "WRITE MAIL NOTIFICATION BOOKING GROUP: ", vals
        """
        Overrides orm write method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        update Hotel Room Reservation line history"""
        if 'noshow_reason_id' in vals:
            noshow_reason_id=vals['noshow_reason_id']
            _logger.info('Notify Hotel and Prime of no show survey submission.')
            self.sudo().send_email_notification('mail_template_etourism_booking_noshow_survey_submission')

        return res

    @api.multi
    def get_checkin_checkout_string(self):
        lang_code = self.env.user.lang or 'en_US'
        lang_ids = self.env['res.lang'].search([('code', '=', lang_code)], limit=1)
        date_format = lang_ids.date_format or DEFAULT_SERVER_DATE_FORMAT

        def formatLangDate(date):
            date = str(datetime.strptime(date, "%Y-%m-%d %H:%M:%S").date())
            date_dt = datetime.strptime(date, DEFAULT_SERVER_DATE_FORMAT)
            return date_dt.strftime(date_format.encode('utf-8')).decode('utf-8')

        result = ''
        for booking in self:
            checkin = str(formatLangDate(booking.checkin))
            checkout = str(formatLangDate(booking.checkout))
            result = ' – '.join([checkin, checkout])
        return result


    @api.multi
    def get_booking_lines_html(self):
        """Format One2many data in mail template's body
        """
        result = ''
        data = u"""
            <tr/>
            <tr>    
                <td> room_categ_id_name </td>
                <td> booking_condition_id_name </td>
                <td style="text-align:left;"> num_rooms </td>
                <td style="text-align:left;"> num_adults </td>
                <td style="text-align:left;"> num_children </td>
                <td style="text-align:left;"> extra_bed </th>
                <td style="text-align:right; padding-right:20px;"> unitary_amount </td>
                <td style="text-align:right;"> total_amount </td>
            </tr>
            """
        for booking in self:
            for line in booking.booking_line:
                res = data
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                unitary_amount = formatLang(self.env, line.unitary_amount, currency_obj=currency_id)
                total_amount = formatLang(self.env, line.amount - line.extra_beds_amount, currency_obj=currency_id)

                res = res.replace('room_categ_id_name', line.sudo().room_id.categ_id.name or '')
                res = res.replace('booking_condition_id_name', line.sudo().booking_condition_id.name or '')
                res = res.replace('num_rooms', line.sudo().room_id and '1' or '0')
                res = res.replace('num_adults', str(line.num_adults) or '0')
                res = res.replace('num_children', str(line.num_children) or '0')
                res = res.replace('extra_bed', str(line.num_extra_bed) or '0')
                res = res.replace('unitary_amount', unitary_amount or '0.00')
                res = res.replace('total_amount', total_amount or '0.00')
                res = res + '\n'
                result = result + res

        subtotal_data = """
                        <tr>    
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td style="text-align:right; padding-right:20px; border-top:1px solid;"> Sub Total: </td>
                            <td style="text-align:right; border-top:1px solid;"> %s </td>
                        </tr>"""%(self.get_subtotal())

        result = result + subtotal_data

        extra_bed_data = """
                        <tr>    
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td style="text-align:right; padding-right:20px; border-top:1px solid;"> Extra Bed Amount: </td>
                            <td style="text-align:right; border-top:1px solid;"> %s </td>
                        </tr>"""%(self.get_extra_bed_amount())

        result = result + extra_bed_data

        amount_data = """
                        <tr>    
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td> </td>
                            <td style="text-align:right; padding-right:20px; border-top:1px solid;"> <strong>Total CVE:</strong> </td>
                            <td style="text-align:right; border-top:1px solid;"> <strong>%s</strong> </td>
                        </tr>"""%(self.get_total_amount())

        result = result + amount_data

        return result

    @api.multi
    def get_subtotal(self):
        total, currency_id = 0.0, False
        for booking in self:
            for line in booking.booking_line:
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                break
            for line in booking.booking_line:
                total += (line.unitary_amount * line.duration)
        total = formatLang(self.env, total, currency_obj=currency_id)
        return total

    @api.multi
    def get_extra_bed_amount(self):
        total, currency_id = 0.0, False
        for booking in self:
            for line in booking.booking_line:
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                break
            for line in booking.booking_line:
                total += line.extra_beds_amount
        total = formatLang(self.env, total, currency_obj=currency_id)
        return total

    @api.multi
    def get_total_amount(self):
        currency_id = False
        for booking in self:
            for line in booking.booking_line:
                currency_id = line.pricelist_item_id.pricelist_id.currency_id
                break
        total = formatLang(self.env, self.total_amount, currency_obj=currency_id)
        return total

    @api.multi
    def send_email_notification(self, email_template=False):
        print "SEND EMAIL NOTIFICATION:::::::::::::::::::::::::::::::::"
        if email_template:
            print "EMAIL TEMPLATE:::::::::::::::::::::::::::::::::",email_template
            ir_model_data = self.env['ir.model.data']
            try:
                template_id = ir_model_data.get_object_reference('etourism_mail_notification', 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 Booking Id: %s'%(email_template, self.id))
        return False

    @api.multi
    def get_ebusiness_contact_emails(self):
        for booking in self:
            ebusiness_id = booking.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_agency_contact_emails(self):
        for booking in self:
            agency_id = booking.agency_id.ebusiness_id
            contact_emails = []
            for contact in agency_id.contacts_line:
                if contact.send_email:
                    contact_emails.append(contact.email)
            return ', '.join(contact_emails)

    @api.multi
    def get_booking_language(self):
        for booking in self:
            booking_language = booking.client_language
            return_language = 'en_GB'
            if booking_language == 'pt':
                return_language = 'pt_PT'
            elif booking_language == 'fr':
                return_language = 'fr_FR'
            return return_language

    @api.multi
    def get_booking_policies(self):
        for booking in self:
            booking_language = booking.client_language
            return_policies = ''
            if booking_language == 'pt':
                return_policies = booking.enterprise_id.policies
            elif booking_language == 'en':
                if booking.enterprise_id.policies_en:
                    return_policies = booking.enterprise_id.policies_en
                else:
                    return_policies = booking.enterprise_id.policies
            elif booking_language == 'fr':
                if booking.enterprise_id.policies_fr:
                    return_policies = booking.enterprise_id.policies_fr
                elif not booking.enterprise_id.policies_fr and booking.enterprise_id.policies_en:
                    return_policies = booking.enterprise_id.policies_en
                else:
                    return_policies = booking.enterprise_id.policies

            return return_policies

    @api.multi
    def get_signup_url(self):
        partner = self.guest_id
        base_url = self.env['ir.config_parameter'].get_param('web.base.url')
        route = 'login'
        # the parameters to encode for the query
        query = dict(db=self.env.cr.dbname)
        #if partner.signup_token and signup_type:
        #    query['token'] = partner.signup_token

        fragment = dict()
        base = '/web#'
        fragment['view_type'] = 'form'
        #fragment['menu_id'] = menu_id
        fragment['model'] = self._name
        fragment['id'] = self.id

        query['redirect'] = base + werkzeug.url_encode(fragment)

        result = urljoin(base_url, "/web/%s?%s" % (route, werkzeug.url_encode(query)))

        return result

    @api.multi
    def get_cancellation_reason(self):
        guest_lang,reason = '',''
        for booking in self:
            guest_lang = booking.guest_id.lang
            if guest_lang == 'pt_PT':
                reason = booking.cancellation_reason_id.name
            elif guest_lang == 'fr_FR':
                reason = booking.cancellation_reason_id.name_fr
            else:
                reason = booking.cancellation_reason_id.name_en
        return reason

    @api.multi
    def action_confirmed(self):
        """Send booking confirmation email to Guest
        """
        res = super(Booking, self).action_confirmed()
        _logger.info('Sending Email notification on booking confirmation. Booking Id: %s'%(self.id))
        print "WILL SEND EMAIL CONFIRMATION:::::::::::::::::::::::::::::::::::::::::"
        self.sudo().send_email_notification('mail_template_etourism_booking_confirmation')
        return res

    '''@api.multi
    def action_cancelled(self):
        """Send booking cancellation email to Guest
        """
        res = super(Booking, self).action_cancelled()
        _logger.info('Sending Email notification on booking cancellation. Booking Id: %s'%(self.id))
        self.sudo().send_email_notification('mail_template_etourism_booking_cancellation')
        return res
		
    @api.multi
    def action_no_show(self):
        """Send booking noshow email to Guest, Hotel and Prime
        """
        res = super(Booking, self).action_no_show()
        _logger.info('Sending Email notification on booking no-show. Booking Id: %s'%(self.id))
        self.sudo().send_email_notification('mail_template_etourism_booking_noshow')
        return res'''