# -*- coding: utf-8 -*-
import werkzeug

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

class enterprise_type_list(http.Controller):

    @http.route(['/tms/restauration','/tms/restauration/page/<int:page>','/tms/restauration/<model("etourism.enterprise"):enterprise_id>'], type='http', auth="public", website=True)
    def index(self,page=1, enterprise_id=None, **searches):
        #print "/tms/restauration: ",page,enterprise_id,searches
        searches.setdefault('default_island', 0)

        if enterprise_id:
            #print "RESTAURATION DETAILS CONTROLLLER: ", enterprise_id, searches
            return request.render('web_etourism_directory.enterprise_restauration_details', {
                'enterprise': enterprise_id,
                'default_island':int(searches['default_island']),
                'island_id':enterprise_id.island_id
            })

        Enterprise = request.env['etourism.enterprise']
        EnterpriseType = request.env['ecom.ebusiness.type']
        Location = request.env['ecom.location']

        step = 10  # Number of interest point per page

        searches.setdefault('search', '')
        searches.setdefault('type', 'all')
        searches.setdefault('island', 'all')
        searches.setdefault('city', 'all')
        searches.setdefault('classification', 'all')

        classifications = [
            ['all', _('All'), [("number_stars", ">=", 0)], 0],
            ['5', _('5 stars'), [("number_stars", "=", 5)], 0],
            ['4', _('4 stars'), [("number_stars", "=", 4)], 0],
            ['3', _('3 stars'), [("number_stars", "=", 3)], 0],
            ['2', _('2 stars'), [("number_stars", "=", 2)], 0],
            ['1', _('1 stars'), [("number_stars", "=", 1)], 0],
        ]

        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["type"] != 'all':
            domain_search["type"] = ['|', ("enterprise_type_id", "=", int(searches["type"])),
                                         ("enterprise_type_id", "=", False)]
        if searches["island"] != 'all':
            domain_search["island"] = ['|', ("island_id", "=", int(searches["island"])), ("island_id", "=", False)]

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

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

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

        result_count = Enterprise.search_count(dom_without(["none"]))

        pager = request.website.pager(
            url="/tms/restauration",
            url_args={
              'search': searches.get('search'),
              'type': searches.get('type'),
              'island': searches.get('island'),
              'default_island': searches.get('default_island'),
              'default_feature': 4
            },
            total=result_count,
            page=page,
            step=step,
            scope=8)

        results = Enterprise.sudo().search(dom_without(["none"]), limit=step, offset=pager['offset'],
                                          order='rating desc,name')
        island_id = None
        if 'island' in domain_search:
            island_id = Location.sudo().search([('id', '=', searches["island"])], limit=1)
        if 'city' in domain_search:
            island_id = Location.sudo().search([('id', '=', searches["city"])], limit=1, offset=pager['offset'],
                                               order='name').parent_id.parent_id.parent_id


        ## FILTERS ##
        types = Enterprise.read_group(dom_without(["none",'type']), ["id", "enterprise_type_id"],
                                              groupby="enterprise_type_id", orderby="enterprise_type_id")

        islands = Enterprise.read_group(dom_without(["none"]), ["id", "island_id"], groupby="island_id",
                                          orderby="island_id")
        #print "ISLAND: ",islands
        cities = Enterprise.read_group(dom_without(["none",'city']), ["id", "local_id"],
                                       groupby="local_id", orderby="local_id")
        #print "CITIES: ", json.dumps(cities)

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

        values = {
            'enterprises': results,
            'pager': pager,
            'island_id': island_id,
            'filtros': filters,
            'default_island': int(searches['default_island']),
            'default_feature': 4
        }
        #print "VALUES: ",values
        return request.render('web_etourism_directory.restorationsList',values)

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

        ## Filter 1
        if types and 'enterprise_type_id' in types[0] and types[0]['enterprise_type_id']:
            filter_items = []
            filter_items.append(
                FilterItem(_('All'), 'all',
                           'checked' if searches['type'] == 'all' else 'unchecked', -1)
            )
            for type in types:
                #print "TYPE: ",type
                if type and type['enterprise_type_id']:
                    filter_items.append(
                        FilterItem(type['enterprise_type_id'][1].split('/')[1], type['enterprise_type_id'][0],
                                   'checked' if searches['type'] == str(type['enterprise_type_id'][0]) else 'unchecked', -1)
                    )

            filters.append(Filter(_('Restauration Type'), 'radio', filter_items, 'type'))

        ## Filter 2
        filter_items = []
        filter_items.append(
            FilterItem(_('All'), 'all',
                       'checked' if searches['island'] == 'all' else 'unchecked', -1)
        )
        for island in islands:
            if island and island['island_id']:
                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 3
        if cities and 'local_id' in cities[0] and cities[0]['local_id']:
            filter_items = []
            filter_items.append(
                FilterItem(_('All'), 'all',
                           'checked' if searches['city'] == 'all' else 'unchecked', -1)
            )
            for city in cities:
                if city and city['local_id']:
                    filter_items.append(
                        FilterItem(city['local_id'][1], city['local_id'][0],
                                   'checked' if searches['city'] == str(city['local_id'][0]) else 'unchecked', -1)
                    )
            filters.append(Filter(_('Cities'), 'radio', filter_items, 'city',not island_id))

        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



