# -*- 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 datetime import date
from odoo.addons.mail.models.mail_template import format_tz
from odoo.exceptions import UserError, ValidationError

import werkzeug
from urlparse import urljoin

class EtourismAVTBooking(models.Model):
    _inherit ='etourism.avt.booking'

    @api.model
    def create(self, vals):
        booking = super(EtourismAVTBooking, self).create(vals)
        booking_id = booking.id
        print "CREATE MAIL NOTIFICATION AVT BOOKING: ", vals
        booking.sudo().send_email()
        return booking

    @api.multi
    def action_confirmed(self):
        self.write({'state': 'confirmed'})
        #self.send_email()
        _logger.info('Sending Email notification on new booking registration. Booking Id: %s' % (self.id))
        self.sudo().send_email_notification('mail_template_etourism_avt_booking')
        return True

    @api.multi
    def action_pay(self):
        self.write({'state': 'paid'})
        self.send_email()
        return True


    @api.multi
    def action_cancelled(self):
        print ("CANCEL BOOKING REGISTRATION")
        self.write({'state': 'cancelled'})
        #self.send_email()
        _logger.info('Sending Email notification on new booking registration. Booking Id: %s' % (self.id))
        self.sudo().send_email_notification('mail_template_etourism_avt_booking')

        return True

    @api.multi
    def action_no_show(self):
        from_dt = date.today()
        datee = datetime.strptime(self.date, '%Y-%m-%d %H:%M:%S').date()
        if from_dt < date:
            raise ValidationError(_('You cannot set a No Show before checkin date.'))
        else:
            self.write({'state': 'no_show'})
            #self.send_email()
            _logger.info('Sending Email notification on new booking registration. Booking Id: %s' % (self.id))
            self.sudo().send_email_notification('mail_template_etourism_avt_booking')

        return True

    @api.multi
    def send_email(self):
        _logger.info('Sending Email notification on new booking registration. Booking Id: %s' % (self.id))
        self.sudo().send_email_notification('mail_template_etourism_avt_booking')
        _logger.info('Sending Email notification on new booking registration (Avt Copy). Booking Id: %s' % (self.id))
        self.sudo().send_email_notification('mail_template_etourism_avt_booking_enterprise')


    @api.multi
    def get_state_text(self, to):
        if self.state == 'pending' and to == 1:
            return _('You Have RECEIVED a Reservation Request.')
        elif self.state == 'confirmed' and to == 1:
            return _('You Have CONFIRMED a Reservation Request.')
        elif self.state == 'cancelled' and to == 1:
            return _('You Have CANCELLED a Reservation Request.')
        elif self.state == 'paid' and to == 1:
            return _('You Have Received a Sucess Booking PAYMENT registration.')
        elif self.state == 'no_show' and to == 1:
            return _('You Have set a Booking Request to NO SHOW')
        elif self.state == 'pending' and to == 0:
            return _('Your Booking Request has been RECEIVED.')
        elif self.state == 'confirmed' and to == 0:
            return _('Your Booking Request is now CONFIRMED')
        elif self.state == 'cancelled' and to == 0:
            return _('Your Booking Request has been CANCELLED.')
        elif self.state == 'paid' and to == 0:
            return _('Your Booking PAYMENT has been registered.')
        elif self.state == 'no_show' and to == 0:
            return _('Your Booking Request change state to NO SHOW')
        else:
            return _('Success')

    @api.multi
    def send_email_notification(self, email_template=False):
        print "send_email_notification"
        if 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 request in self:
            ebusiness_id = request.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_signup_url(self):
        partner = self.client_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_date_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')

        date = ''
        for request in self:
            date = str(formatLangDate(request.date))

        return date

    @api.multi
    def get_booking_lines_html(self):
        """Format One2many data in mail template's body
        """
        result = ''
        data = u"""
                    <tr>
                        <td> date </td>     
                        <td> package_name </td>
                        <td> package_category </td>
                        <td style="text-align:left;"> num_pax </td>
                        <td style="text-align:right; padding-right:20px;"> unitary_amount </td>
                        <td style="text-align:right;"> total_amount </td>
                    </tr>
                    """
        for booking in self:
            res = data
            currency_id = booking.pricelist_item_id.pricelist_id.currency_id
            unitary_amount = formatLang(self.env, booking.unitary_amount, currency_obj=currency_id)
            total_amount = formatLang(self.env, booking.total_amount, currency_obj=currency_id)

            res = res.replace('date', booking.sudo().date or '')
            res = res.replace('package_category', booking.sudo().package_id.package_type_id.name or '')
            res = res.replace('package_name', booking.sudo().package_id.name or '')
            res = res.replace('num_pax', str(booking.sudo().num_pax) 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 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

        if self.discount_amount > 0:
            discount_data = """
                                            <tr>    
                                                <td> </td>
                                                <td> </td>
                                                <td> </td>
                                                <td> </td>
                                                <td style="text-align:right; padding-right:20px; border-top:1px solid;">Voucher (%s) Discount: </td>
                                                <td style="text-align:right; border-top:1px solid;"> %s </td>
                                            </tr>""" % (self.voucher_id.name, formatLang(self.env, self.discount_amount,
                                                                                         currency_obj=booking.pricelist_item_id.pricelist_id.currency_id))

            result = result + discount_data
        amount_data = """
                                <tr> 
                                    <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

