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

import logging
import werkzeug
from itertools import groupby

from odoo import fields, http, _, SUPERUSER_ID

from odoo.http import request

_logger = logging.getLogger(__name__)

class Result:

    def __init__(self, row, group,item=None,places=None):
        self.row = list(row)
        self.group = group
        self.item = item
        self.places = places

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

    ## ROUTES HANDLERS ##

    # Services list
    @http.route(['/services', '/services/page/<int:page>','/services/<model("pasp.service"):service>'], type='http', auth="public", website=True)
    def terms_list(self,page=1,service=None, **searches):
        print "START Terms LIST::::::::::::::::::::::::::::::::::::::::::::::::: ",searches,page,service
        # Controls if the customer can be displayed

        if not service:
            cr = request.cr
            searches.setdefault('search', '')

            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)]

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

            Services = request.env['pasp.service']

            step = 20  # Number of events per page
            terms_count = Services.search_count(dom_without("none"))
            pager = request.website.pager(
                url="/services",
                url_args={'search': searches.get('search')},
                total=terms_count,
                page=page,
                step=step,
                scope=8)

            order = 'categ_id,name'
            terms = Services.sudo().search(dom_without("none"), limit=step, offset=pager['offset'], order=order)
            results = []

            if terms:
                for group, row in groupby(terms, key=lambda x: x['categ_id']):
                    results.append(Result(row, group))

                print "RESULTS: ", results[0].row

            pasp_countries = request.env['res.country'].sudo().search([('is_pasp', '=', True)])
            print "PASP COUNTRIES: ", pasp_countries

            values = {
                'search': searches['search'],
                'results': results,
                'pager': pager,
                'searches': searches,
                'pasp_countries':pasp_countries,
                'search_path': "?%s" % werkzeug.url_encode(searches),
            }

            return request.render('search_snippet.search_result',values)

        else:
            service_entity_rel = request.env['pasp.service.entity'].sudo().search([('service_id', '=', service.id)])
            categ_services = request.env['pasp.service'].sudo().search([('categ_id', '=', service.categ_id.id)])

            print "######################## SERVICES FROM CATEG: ",categ_services
            contacts = []

            if service_entity_rel:
                entities = [rel.entity_id for rel in service_entity_rel]

                if entities:
                    for k, v in groupby(entities, key=lambda x: x['country_id']):
                        contacts.append(Result(v, k))
                    contacts = sorted(contacts, key=lambda entity: entity.group.name)

            result = Result(categ_services, service.categ_id,service,contacts)
            values = {
                'result': result,
                'search': service.name
            }
            return request.render('search_snippet.search_result_detail', values)