# -*- coding: utf-8 -*-
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response

from paginator import SamplePaginator
import urllib
import ast
from sampleapp import helper

SOLR_SELECT_URL = getattr(settings, "SOLR_SELECT_URL", "http://localhost:8983/solr/select")

def index(request):
  # getparam
  params = request.POST or request.GET
  q = params.get('query')
  if not q:
    q = '*:*'
  else:
    q = q.encode('UTF-8')

  fq = params.getlist('fq')
  filters = fq
  
  solr_params = [
    ('q',q),
    ('wt','python') ,
    ('json.nl','arrmap') ,
    ('start',params.get('start') or 0),
    ('rows',params.get('rows') or 10),
    ('fl','url,title,price,author,pages,isbn'),
    ('hl','true'),
    ('hl.fl','title,summary,intended_reader,from_author,toc'),
    ('hl.snipetts','1'),
    ('f.title.hl.alternateField','title'),
    ('f.summary.hl.alternateField','summary'),
    ('f.summary.hl.maxAlternateFieldLength','100'),
    ('hl.usePhraseHighlighter','true'),
    ('hl.simple.pre','<b style="background:aquamarine">'),
    ('hl.simple.post','</b>'),
    ('facet','true'),
    ('facet.limit','20'),
    ('facet.mincount','1'),
    ('facet.sort','count'),
  ]
  if helper.FACET_LABELS.keys():
    for field in helper.FACET_LABELS.keys():
      solr_params.append(('facet.field',field))
  if filters:
    for query in filters:
      solr_params.append(('fq',query.encode('UTF-8')))
  if helper.get_facet_queries_array():
    for query in helper.get_facet_queries_array():
      solr_params.append(('facet.query',query))
    
  encoded_params = urllib.urlencode(solr_params)
  
  # request to solr
  conn = urllib.urlopen(SOLR_SELECT_URL+'?%s' % encoded_params)
  solr_res = ast.literal_eval(conn.read())
  # < For python 2.6
  #solr_res = eval(conn.read())

  # result
  found = int(solr_res['response']['numFound']) or 0
  start = int(solr_res['responseHeader']['params']['start']) or 0
  rows = int(solr_res['responseHeader']['params']['rows']) or 10
  qtime = solr_res['responseHeader']['QTime'] or 0
  ends = start + rows
  if qtime > 0:
    qtime = float(qtime)/1000
  if ends > found:
    ends = found
  inparams = dict(params.items())
  if inparams.has_key('fq'):
    inparams['fq'] = filters
  paginator = SamplePaginator(start,rows,found)
  
  c = ({'inparams':inparams,
        'rsp':solr_res,
        'found':found,
        'start':start,
        'rows':rows,
        'ends':ends,
        'qtime':qtime,
        'master_queries':helper.FACET_QUERIES,
        'paginator':paginator})


  return render_to_response('index.html',c)
