#! /usr/bin/env ruby

require 'rbconfig'
require 'yaml'
require 'rdoc/ri/descriptions'
require 'rdoc/markup/to_flow'
require 'net/http'
require 'fileutils'

items_cache_dir = File.expand_path('~/.fasteri/items')
FileUtils.mkdir_p(items_cache_dir)
index_cache = File.expand_path('~/.fasteri/index')

data = ""

if ARGV.size == 1
  item = ARGV[0]
  fname = "#{items_cache_dir}/#{item.gsub(/:+/, '-')}"
  unless File.exists?(fname)
    data = `ri -T #{item}`

    File.open(fname, "w") do |io|
      io.puts data
    end
  else
    File.open(fname, "r") do |io|
      data = io.read
    end
  end
else
  unless File.exists?(index_cache)
    ver = RbConfig::CONFIG["ruby_version"]
    m = /ruby/.match(RbConfig::CONFIG["RUBY_INSTALL_NAME"])
    ri = "#{m.pre_match}ri#{m.post_match}"
    path = File.join(RbConfig::CONFIG["datadir"], ri, ver)

    Dir.chdir(path)
    pipe = IO.popen("find -wholename '*/cdesc*.yaml' -print")
    info = []
    pipe.read.split.each do |name|
      cdesc = File.open(name) { |io| YAML.load(io) }
      if cdesc
        info << cdesc.full_name
        cdesc.class_methods.each do |method|
          info << "#{cdesc.full_name}##{method.name}"
        end
        cdesc.instance_methods.each do |method|
          info << "#{cdesc.full_name}##{method.name}"
        end
      end
    end

    data = info.uniq.compact.join("\n")
    File.open(index_cache, "w") do |io|
      io.puts data
    end
  else
    File.open(index_cache, "r") do |io|
      data = io.read
    end
  end
end

puts data
