#!/usr/bin/env ruby
#
# Generate a Ruby version of an RDFa vocabulary to be directly accessible from RDF::RDFa::Profile
require 'rubygems'
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), "..", 'lib')))
require 'linkeddata'
require 'getoptlong'
require 'open-uri'

def help
  puts "Usage: #{$0} [options] file-or-uri ..."
  puts "Options:"
  puts "      --dump:               Dump raw output, otherwise serialize to Ruby"
  puts "      --debug:              Display detailed debug output"
  puts "      --verbose:            Verbose processing"
  puts "      --output:             Write to file"
  puts "      --help,-?:            This message"
  exit(0)
end

dump = false
output = STDOUT

opts = GetoptLong.new(
  ["--debug", GetoptLong::NO_ARGUMENT],
  ["--dump", GetoptLong::NO_ARGUMENT],
  ["--output", "-o", GetoptLong::REQUIRED_ARGUMENT],
  ["--verbose", GetoptLong::NO_ARGUMENT],
  ["--help", "-?", GetoptLong::NO_ARGUMENT]
)
opts.each do |opt, arg|
  case opt
  when '--verbose'  then $verbose = true
  when '--debug'    then ::RDF::RDFa::debug = true
  when '--dump'     then dump = true
  when '--output'   then output = File.open(arg, "w")
  when '--help'     then help
  end
end

help if ARGV.empty?

ARGV.each do |file|
  uri = RDF::URI(file)
  if RDF::RDFa::Profile.cache[uri]
    STDERR.puts "Remove cached entry for #{uri} before attempting to parse"
    exit(1)
  end
  
  profile = RDF::RDFa::Profile.find(uri)
  if dump
    puts profile.inspect
  else
    output.puts  <<START
# This file is automatically generated by #{__FILE__}
# RDFa vocabulary for #{file}

profile = RDF::RDFa::Profile.new(RDF::URI("#{file}"), {
START

    output.puts %{  :vocabulary => "#{profile.vocabulary},"} if profile.vocabulary
    
    [:prefixes, :terms].each do |t|
      hash = profile.send(t)
      key_width = hash.keys.inject(0) {|width, k| k.inspect.length > width ? k.inspect.length : width}
      unless hash.empty?
        output.puts %(  :#{t} => {)
          hash.keys.map(&:to_s).sort.each do |k|
            v = hash[k.to_sym]
            output.printf(%(    %*s => %s,\n), -key_width, k.to_sym.inspect, v.inspect)
          end
        output.puts %(  },)
      end
    end
    
    output.puts <<END
})

RDF::RDFa::Profile.cache[RDF::URI("#{file}")] = profile
END

  end
end