require 'solr'

class SearchController < ApplicationController

  def initialize
    @solr = Solr::Connection.new( 'http://localhost:8983/solr' )
    @facet_queries = {
      '発売年' => [
        {'pub_date:[20090101 TO *]'=>'2009年以降'},
        {'pub_date:[20080101 TO 20081231]'=>'2008年'},
        {'pub_date:[20070101 TO 20071231]'=>'2007年'},
        {'pub_date:[20060101 TO 20061231]'=>'2006年'},
        {'pub_date:[20050101 TO 20051231]'=>'2005年'},
        {'pub_date:[* TO 20041231]'=>'2004年以前'},
      ],
    }
    @fq_array = []
    @facet_queries.each do |k,queries|
      queries.each do |query|
        query.each do |ffk,ffv|
	  @fq_array << ffk
        end
      end
    end
  end

  def index
    @response = search( params )
  end

  private

  def search( p = {} )
    @query = p['query'] || '*:*'
    @query = '*:*' if @query.empty?
    @filters = ( p[:filters] || "" ).split( /\// )
    prm = {
      :start => p[:start] || 0,
      :rows => p[:rows] || 10,
      :filter_queries => @filters,
      :field_list => [:url, :author, :price, :pages, :isbn],
      :facets => {
        :fields => [:genre,:keyword,:author_facet], :limit => 20, :mincount => 1, :sort => :count,
        :queries => @fq_array,
      },
      :highlighting => {
        :field_list => [:title,:summary,:intended_reader,:from_author,:toc],
        :max_snippets => 1,
        :alternate_fields => { :title => :title, :summary => :summary },
        :max_alternate_field_length => { :summary => 100 },
        :use_phrase_highlighter => true
      }
    }
    @solr.query( @query, prm ).data
  end

end
