require 'livesearch'
require 'mpd'
require 'time'

def time str=nil, &block
  if str
    print str
    finish = nil
    thr = Thread.new do
      until finish
        sleep 0.1
        print "."
      end
    end
  end
  start = Time.now
  r = yield
  finish = Time.now
  thr.terminate if thr
  t = finish - start
  puts t if str
  t
end

def benchmark ss=10, &block
  pool = (1..ss).map {|s| time nil, &block}
  pool.inject {|a,b| (a + b)/2}
end
  
m = MPD.new
str = "collective soul youth"

time "Second: " do sleep 1 end

time "Mapping: " do
  $list = m.playlistinfo.map {|i| [:title,:artist,:album,:file].map {|j| i.send(j).to_s}.join(" ")}
end

plain = LiveSearch.new m.playlistinfo do |i,r|
  [:artist,:album,:title,:file].any? do |f|
    r.match i.send(f).to_s
  end
end
map = LiveSearch.new $list

print "With mapping: "
tmp = ""
str.split(//).each do |l|
  tmp = tmp + l
  puts (time do map.search(tmp) end).to_s.ljust(10) + "\t#{tmp}"
end

print "No mapping: "
tmp = ""
str.split(//).each do |l|
  tmp = tmp + l
  puts (time do plain.search(tmp) end).to_s.ljust(10) + "\t#{tmp}"
end
