# 1. Index using rake index
# 2. Start with rake start
# 3. curl '127.0.0.1:8080/all?query=bla'
#

# Stresstest using
#   ab -kc 5 -t 5 http://127.0.0.1:4567/csv?query=t
#

require 'sinatra/base'
require 'active_record'
require 'csv'
require File.expand_path '../lib/picky', __dir__ # Use the current state of Picky.

require_relative 'project'

class BookSearch < Sinatra::Application
  weights = {
    [:author] => +6,
    %i[title author] => +5,
    %i[author year] => +2
  }

  {
    books: Picky::Search.new(BooksIndex, ISBNIndex) do
      boost weights
    end,
    books_ignoring: Picky::Search.new(BooksIndex, ISBNIndex) do
      boost weights
      ignore_unassigned_tokens true
    end,
    book_each: Picky::Search.new(BookEachIndex) do
      boost weights
      ignore :title
    end,
    redis: Picky::Search.new(RedisIndex) do
      boost weights
    end,
    memory_changing: Picky::Search.new(MemoryChangingIndex),
    redis_changing: Picky::Search.new(RedisChangingIndex),
    csv: Picky::Search.new(CSVIndex) do
      boost weights
    end,
    isbn: Picky::Search.new(ISBNIndex),
    sym: Picky::Search.new(SymKeysIndex),
    geo: Picky::Search.new(RealGeoIndex),
    simple_geo: Picky::Search.new(MgeoIndex),
    iphone: Picky::Search.new(IphoneLocations),
    indexing: Picky::Search.new(IndexingIndex),
    file: Picky::Search.new(FileIndex),
    japanese: Picky::Search.new(JapaneseIndex) do
      searching removes_characters: /[^\p{Han}\p{Katakana}\p{Hiragana}"~*:,]/i, # a-zA-Z0-9\s\/\-\_\&\.
                stopwords: /\b(and|the|of|it|in|for)\b/i,
                splits_text_on: %r{[\s/\-&]+}
    end,
    nonstring: Picky::Search.new(NonstringDataIndex),
    partial: Picky::Search.new(PartialIndex),
    sqlite: Picky::Search.new(SQLiteIndex),
    commas: Picky::Search.new(CommaIdsIndex),
    all: Picky::Search.new(BooksIndex, CSVIndex, ISBNIndex, MgeoIndex) do
      boost weights
    end
  }.each do |(path, things)|
    get %r{/#{path}} do
      things.search(params[:query], params[:ids] || 20, params[:offset] || 0).to_json
    end
  end

  # Live.
  #
  live = Picky::Interfaces::LiveParameters::Unicorn.new
  get '/admin' do
    results = live.parameters params
    results.to_json
  end
end
