# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import json
import logging
import werkzeug
from datetime import datetime
from math import ceil

from odoo import fields, http, SUPERUSER_ID
from odoo.http import request
from odoo.tools import ustr

_logger = logging.getLogger(__name__)


class WebsiteNoShow(http.Controller):
    # HELPER METHODS #

    def _check_bad_cases(self, booking_group, token=None):
        # In case of bad survey, redirect to surveys list
        if not booking_group.sudo().exists():
            return werkzeug.utils.redirect("/noshow/")

        # In case of non no_show bookings
        if booking_group.state!='no_show':
            return request.render("etourism.notnoshow")

        # Everything seems to be ok
        return None

    # Survey displaying
    @http.route(['/noshow/<model("etourism.booking.group"):booking_group>/<string:token>',
                 '/noshow/<model("etourism.booking.group"):booking_group>/<string:token>'],
                type='http', auth='public', website=True)
    def fill_noshow(self, booking_group, token, **post):
        BookingGroup = request.env['etourism.booking.group']
        Reason = request.env['etourism.noshow.reason']
        domain=[]
        reasons = Reason.sudo().search([])

        #print "LEN REASONS::::::::::",len(reasons)
        #print "#1:::::::::::::::::::::::"
        # Controls if the survey can be displayed
        errpage = self._check_bad_cases(booking_group)
        if errpage:
            return errpage
        #print "#2:::::::::::::::::::::::"

        # Load the book_grp
        try:
            #print "#3:::::::::::::::::::::::"
            #print "BOOKING ID:::::::::::::::::::::::",booking_group.id
            book_grp = BookingGroup.sudo().search([('id', '=', booking_group.id),('noshow_token', '=', token)], limit=1)
        except IndexError:  # Invalid token
            #print "#4:::::::::::::::::::::::"
            return request.render("website.403")
        #print "#5:::::::::::::::::::::::"

        # Select the right page
        if book_grp.state == 'no_show':
            #print "#6:::::::::::::::::::::::"
            if book_grp.noshow_state == 'unanswered':
                data = {'booking_group': booking_group,'token': book_grp.noshow_token,'reasons':reasons}
                return request.render('etourism.survey', data)
            elif book_grp.noshow_state == 'answered':  # Display success message
                return request.render('etourism.sfinished', {'booking_group': booking_group,
                                                               'token': token})
        else:
            #print "#7:::::::::::::::::::::::"
            return request.render("website.403")

    # AJAX submission of a survey
    @http.route(['/noshow/submit/<model("etourism.booking.group"):booking_group>'], type='http', methods=['POST'], auth='public', website=True)
    def submit(self, booking_group, **post):
        _logger.debug('Incoming data: %s', post)
        #print "SUBMIT #1:::::::::::::::::::::::",post

        # Answer validation
        errors = {}

        ret = {}
        if len(errors):
            #print "SUBMIT #2:::::::::::::::::::::::"
            # Return errors messages to webpage
            ret['errors'] = errors
        else:
            # Store answers into database
            #print "SUBMIT #3:::::::::::::::::::::::"
            try:
                book_grp = request.env['etourism.booking.group'].sudo().search([('id', '=', booking_group.id),('noshow_token', '=', post['token'])], limit=1)
            except KeyError:  # Invalid token
                return request.render("website.403")
            user_id = SUPERUSER_ID
            #print "SUBMIT #4:::::::::::::::::::::::"

            vals = {'noshow_state': 'answered'}
            reason_id = post['reason']
            noshow_obs = post['noshow_obs']
            #print "SUBMIT REASON ID:::::::::::::::::::::::",reason_id
            #print "SUBMIT OBS:::::::::::::::::::::::",noshow_obs
            vals.update({'noshow_reason_id':reason_id,'noshow_obs':noshow_obs})
            #print "SUBMIT #5:::::::::::::::::::::::"

            book_grp.sudo(user=user_id).write(vals)
            #print "SUBMIT #6:::::::::::::::::::::::"
            ret['redirect'] = '/noshow/%s/%s' % (booking_group.id, post['token'])
            #print "SUBMIT #7:::::::::::::::::::::::"
        return request.render('etourism.sfinished', {'booking_group': booking_group,'token': post['token']})
