"""
search.py
"""
from flask import Flask, request, redirect, abort, make_response
from flask import render_template, flash
import bibserver.dao
from bibserver import auth
import json, httplib
from bibserver.config import config
import bibserver.util as util

import logging
from logging.handlers import RotatingFileHandler

LOG_FILENAME="./app.log"
log = logging.getLogger('werkzeug')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(
   "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
handler = RotatingFileHandler(LOG_FILENAME, maxBytes=10000000, backupCount=5)
handler.setFormatter(formatter)
log.addHandler(handler)

class Search(object):

    def __init__(self,path,current_user):
        self.path = path.replace(".json","")
        self.current_user = current_user

        # facets -> convert to aggs
        self.search_options = {
            'search_url': '/query?',
            'search_index': 'elasticsearch',
            'paging': { 'from': 0, 'size': 10 },
            #'predefined_filters': {},
            #'facets': config['search_facet_fields'],
            'result_display': config['search_result_display'],
            'search_sortby': [{'display':'year', 'field':'year.exact'},
                {'display':'author','field':'author.name'},
                {'display':'journal','field':'journal.name'}],
            'searchbox_fieldselect': [
                {'display':'author','field':'author.name'},
                {'display':'journal','field':'journal.name'}]#,
            #'addremovefacets': config['add_remove_facets']      # (full list could also be pulled from DAO)
        }

        self.parts = self.path.strip('/').split('/')


    def find(self):
        log.debug(self.parts[0])
        log.debug(self.parts)
        log.debug(len(self.parts))
        if bibserver.dao.Account.get(self.parts[0]):
            if len(self.parts) == 1:
                return self.account() # user account
            elif len(self.parts) == 2:
                if self.parts[1] == "collections":
                    return self.collections()
                else:
                    return self.collection() # get a collection
            elif len(self.parts) == 3:
                return self.record() # get a record in collection
        elif self.parts[0] == 'collections':
            return self.collections() # get search list of all collections
        elif len(self.parts) == 1:
            if self.parts[0] != 'search':
                self.search_options['q'] = self.parts[0]
            return self.default() # get search result of implicit search term
        elif len(self.parts) == 2:
            return self.implicit_facet() # get search result of implicit facet filter
        else:
            abort(404)

    def default(self):
        # default search page
        if util.request_wants_json():
            res = bibserver.dao.Record.query()
            resp = make_response(
                json.dumps([i['_source'] for i in res._hits],
                            sort_keys=True, indent=4) )
            resp.mimetype = "application/json"
            return resp
        else:
            return render_template('search/index.html', 
                current_user=self.current_user, 
                search_options=json.dumps(self.search_options), 
                collection=None
            )
        
    
    
    
    # TODO: convert facet => aggs
    def implicit_facet(self):
        self.search_options['predefined_filters'][self.parts[0]+config['facet_field']] = self.parts[1]
        # remove the implicit facet from facets
        for count,facet in enumerate(self.search_options['facets']):
            if facet['field'] == self.parts[0]+config['facet_field']:
                del self.search_options['facets'][count]
        if util.request_wants_json():
            res = bibserver.dao.Record.query(terms=self.search_options['predefined_filters'])
            resp = make_response( json.dumps([i['_source'] for i in res._hits], sort_keys=True, indent=4) )
            resp.mimetype = "application/json"
            return resp
        else:
            return render_template('search/index.html', 
                current_user=self.current_user, 
                search_options=json.dumps(self.search_options), 
                collection=None, 
                implicit=self.parts[0]+': ' + self.parts[1]
            )


    def collections(self):
        if len(self.parts) == 1:
            if util.request_wants_json():
                res = bibserver.dao.Collection.query(size=1000000)
                colls = [i['_source'] for i in res._hits]
                resp = make_response( json.dumps(colls, sort_keys=True, indent=4) )
                resp.mimetype = "application/json"
                return resp
            else:
                # search collection records
                self.search_options['search_url'] = '/query/collection?'
                self.search_options['facets'] = [{'field':'owner','size':100},{'field':'_created','size':100}]
                self.search_options['result_display'] = [[{'pre':'<h3>','field':'label','post':'</h3>'}],[{'field':'description'}],[{'pre':'created by ','field':'owner'}]]
                self.search_options['result_display'] = config['collections_result_display']
                return render_template('collection/index.html', current_user=self.current_user, search_options=json.dumps(self.search_options), collection=None)
        elif len(self.parts) == 2:
            if self.parts[0] == "collections":
                acc = bibserver.dao.Account.get(self.parts[1])