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


import werkzeug
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo.addons.website_event.controllers.main import WebsiteEventController
from odoo.addons.prime_snippets.models.filter import Filter, FilterItem
from odoo import fields, http, _
from odoo.http import request

class WebsiteEventController(WebsiteEventController):

    @http.route(['/event/<model("event.event"):event>/register'], type='http', auth="public", website=True)
    def event_register(self, event, **searches):
        print "POST: ",event
        searches.setdefault('default_island', 0)
        values = {
            'event': event,
            'main_object': event,
            'range': range,
            'island_id':event.island_id,
            'registrable': event._is_event_registrable(),
            'default_island': int(searches['default_island'])
        }
        return request.render("website_event_tourism.event_description_full", values)

    @http.route(['/event', '/event/page/<int:page>', '/events', '/events/page/<int:page>'], type='http', auth="public",
                website=True)
    def events(self, page=1, **searches):
        print "EVENTS CONTROLLER: ",page,searches
        Event = request.env['event.event']
        Location = request.env['ecom.location']
        EventType = request.env['event.type']

        searches.setdefault('default_island', 0)
        searches.setdefault('date', 'all')
        searches.setdefault('island', 'all')
        searches.setdefault('type', 'all')

        domain_search = {}

        print "#################### EVENTS: ", page, searches

        def sdn(date):
            return fields.Datetime.to_string(date.replace(hour=23, minute=59, second=59))

        def sd(date):
            return fields.Datetime.to_string(date)

        today = datetime.today()

        dates = [
            ['all', _('Next Events'), [("date_end", ">", sd(today))], 0],
            ['today', _('Today'), [
                ("date_end", ">", sd(today)),
                ("date_begin", "<", sdn(today))],
             0],
            ['week', _('This Week'), [
                ("date_end", ">=", sd(today + relativedelta(days=-today.weekday()))),
                ("date_begin", "<", sdn(today + relativedelta(days=6 - today.weekday())))],
             0],
            ['nextweek', _('Next Week'), [
                ("date_end", ">=", sd(today + relativedelta(days=7 - today.weekday()))),
                ("date_begin", "<", sdn(today + relativedelta(days=13 - today.weekday())))],
             0],
            ['month', _('This month'), [
                ("date_end", ">=", sd(today.replace(day=1))),
                ("date_begin", "<", (today.replace(day=1) + relativedelta(months=1)).strftime('%Y-%m-%d 00:00:00'))],
             0],
            ['nextmonth', _('Next month'), [
                ("date_end", ">=", sd(today.replace(day=1) + relativedelta(months=1))),
                ("date_begin", "<", (today.replace(day=1) + relativedelta(months=2)).strftime('%Y-%m-%d 00:00:00'))],
             0],
            ['old', _('Old Events'), [
                ("date_end", "<", today.strftime('%Y-%m-%d 00:00:00'))],
             0],
        ]

        # search domains
        # TDE note: WTF ???
        current_date = None
        for date in dates:
            if searches["date"] == date[0]:
                domain_search["date"] = date[2]
                if date[0] != 'all':
                    current_date = date[1]

        if searches["island"] != 'all':
            domain_search["island"] = ['|', ("island_id", "=", int(searches["island"])), ("island_id", "=", False)]

        if searches["type"] != 'all':
            domain_search["type"] = ['|', ("event_type_id", "=", int(searches["type"])),
                                         ("event_type_id", "=", False)]

        def dom_without(without):
            domain = [('state', "in", ['draft', 'confirm', 'done'])]
            for key, search in domain_search.items():
                if key != without:
                    domain += search
            return domain

        # count by domains without self search
        for date in dates:
            date[3] = Event.search_count(dom_without('date') + date[2])


        step = 10  # Number of events per page
        print "SEARCH COUNT: ",dom_without("none")
        event_count = Event.search_count(dom_without("none"))
        pager = request.website.pager(
            url="/event",
            url_args={
                'date': searches.get('date'),
                'island': searches.get('island'),
                'type': searches.get('type'),
                'default_island': searches.get('default_island'),
                'default_feature':2
            },
            total=event_count,
            page=page,
            step=step,
            scope=5)

        order = 'website_published desc, date_begin'
        if searches.get('date', 'all') == 'old':
            order = 'website_published desc, date_begin desc'
        events = Event.search(dom_without(["none"]), limit=step, offset=pager['offset'], order=order)

        islands = Event.read_group(dom_without(["none"]), ["id", "island_id"], groupby="island_id",
                                          orderby="island_id")

        island_id = None
        if 'island' in domain_search:
            island_id = Location.sudo().search([('id', '=', searches["island"])], limit=1)
        print "EVENTS: ",island_id

        types = Event.read_group(dom_without(["none",'type']), ["id", "event_type_id"],
                                              groupby="event_type_id", orderby="event_type_id")

        type_id = None
        if 'type' in domain_search:
            type_id = EventType.sudo().search([('id', '=', searches["type"])], limit=1)
        print "Type: ",type_id

        filters = self.build_filters(searches, dates,types,islands,island_id)

        values = {
            'current_date': current_date,
            'events': events,  # event_ids used in website_event_track so we keep name as it is
            'dates': dates,
            'island_id':island_id,
            'type_id':type_id,
            'pager': pager,
            'searches': searches,
            'search_path': "?%s" % werkzeug.url_encode(searches),
            'filtros': filters,
            'default_island': int(searches['default_island']),
            'default_feature': 2
        }

        return request.render("website_event_tourism.events_index", values)

    def build_filters(self, searches, dates,types,islands,island_id):
        filters = []

        filter_items = []
        for date_filter in [list((date[0], date[1], date[3])) for date in dates]:
            if date_filter:
                if date_filter[2]!=0:
                    filter_items.append(
                        FilterItem(date_filter[1], date_filter[0],
                                   'checked' if searches['date'] == str(date_filter[0]) else 'unchecked',
                                   date_filter[2])
                    )

        filters.append(Filter('Temporal', 'radio', filter_items, 'date'))

        ## Filter Islands
        filter_items = []
        filter_items.append(
            FilterItem(_('All'), 'all',
                       'checked' if searches['island'] == 'all' else 'unchecked', -1)
        )
        for island in islands:
            if island:
                filter_items.append(
                    FilterItem(island['island_id'][1], island['island_id'][0],
                               'checked' if searches['island'] == str(island['island_id'][0]) else 'unchecked', -1)
                )

        filters.append(Filter(_('Islands'), 'radio', filter_items, 'island', island_id or not islands))

        ## Filter 2
        filter_items = []
        filter_items.append(
            FilterItem(_('All'), 'all',
                       'checked' if searches['type'] == 'all' else 'unchecked', -1)
        )
        for type in types:
            if type:
                filter_items.append(
                    FilterItem(type['event_type_id'][1], type['event_type_id'][0],
                               'checked' if searches['type'] == str(type['event_type_id'][0]) else 'unchecked', -1)
                )
        filters.append(Filter(_('Categories'), 'radio', filter_items, 'type'))

        default_island_filter = [
            FilterItem('default', searches['default_island'], 'checked' if searches['default_island'] else 'unchecked',
                       -1)]
        filters.append(Filter('Default Island', 'radio', default_island_filter, 'default_island', True))

        return filters