# -*- coding: utf-8 -*-
import werkzeug
from itertools import groupby

from odoo import fields, http, _
from odoo.http import request
from odoo.addons.prime_snippets.models.filter import Filter, FilterItem
import json


class InterestPointController(http.Controller):

    # Interest Points List
    @http.route(['/tms/places','/tms/places/page/<int:page>','/tms/places/<model("etourism.directory.interest.point"):place_id>'],type='http', auth="public", website=True)
    def index(self, page=1, place_id=None, **searches):
        #print "INTEREST POINT CONTROLLLER: ", place_id,page,searches
        searches.setdefault('default_island', 0)
        lang = request.context["lang"]
        #print "INTEREST POINT CONTROLLLER LANG: ",lang

        if place_id:
            #print "INTEREST POINT DETAILS CONTROLLLER: ", place_id, searches
            return request.render('web_etourism_directory.interest_point_details', {
                'interest_point': place_id,
                'default_island':int(searches['default_island']),
                'island_id':place_id.place_id
            })

        InterestPoint = request.env['etourism.directory.interest.point']
        Location = request.env['ecom.location']
        step = 9  # Number of interest point per page

        searches.setdefault('search', '')
        searches.setdefault('category', 'all')
        searches.setdefault('island', 'all')
        searches.setdefault('tag', 'all')

        domain_search = {}

        # search domains
        current_search = None

        if searches["search"]:
            current_search = searches['search']
            for srch in searches["search"].split(" "):
                domain_search["search"] = [('name', 'ilike', srch)]

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

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

        def dom_without(without):
            domain = []
            for key, search in domain_search.items():
                if key not in without:
                    domain += search
            return domain

        result_count = InterestPoint.search_count(dom_without(["none"]))
        #print "SEARCHES DOMAIND: ",searches
        pager = request.website.pager(
            url="/tms/places",
            url_args={
                'search': searches.get('search'),
                'category': searches.get('category'),
                'island': searches.get('island'),
                'tag': searches.get('tag'),
                'default_island': searches.get('default_island'),
                'default_feature': 3,
            },
            total=result_count,
            page=page,
            step=step,
            scope=8)

        results = InterestPoint.sudo().search(dom_without(["none"]), limit=step, offset=pager['offset'], order='place_id,category_id,name')
        island_id = None
        if 'island' in domain_search:
            #print "SEARCHES ISLAND: ",searches["island"]
            island_id = Location.sudo().search([('id','=',searches["island"])], limit=1)

        ## FILTERS ##
        categories = InterestPoint.read_group(dom_without(["none",'category']), ["id", "category_id"],
                                              groupby="category_id", orderby="category_id")
        places = InterestPoint.read_group(dom_without(["none"]), ["id", "place_id"], groupby="place_id",
                                          orderby="place_id")

        #print "CATEGORIES: ",json.dumps(categories)
        filters = self.build_filters(searches,categories,places,island_id)

        values ={
            'interest_points':results,
            'pager':pager,
            'island_id':island_id if island_id else None,
            'filtros':filters,
            'default_island': int(searches['default_island']),
            'default_feature': 3,
            'page_lang': lang
        }

        #print "VALUES: ",island_id
        return request.render('web_etourism_directory.interest_point_index', values)

    def build_filters(self, searches, categories, places,island_id):
        filters = []

        ## Filter 1
        filter_items = []
        filter_items.append(
            FilterItem(_('All'), 'all',
                       'checked' if searches['island'] == 'all' else 'unchecked', -1)
        )
        for country in places:
            if country:
                filter_items.append(
                    FilterItem(country['place_id'][1], country['place_id'][0],
                               'checked' if searches['island'] == str(country['place_id'][0]) else 'unchecked', -1)
                )
        filters.append(Filter(_('Islands'), 'radio', filter_items, 'island',island_id or not places))

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

        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
