#!/usr/bin/env ruby

require 'optparse'
require 'heroics'
require 'open-uri'

options = {headers: {}, cache_path: nil}
option_parser = OptionParser.new do |opts|
  opts.banner = <<-EOS
Usage: heroics-generate module_name schema_filepath url
       heroics-generate configuration-file-path.rb
# Params only allowed when using the first form:
EOS

  opts.on('-h', '--help', 'Display this screen') do
    puts opts
    exit
  end

  opts.on('-H', '--header [HEADER]',
          'Include header with all requests') do |header|
    parts = header.split(':', 0)
    options[:headers][parts[0]] = parts[1].strip
  end

  opts.on('-c', '--cache-dir [PATH]',
          'Content cache directory (~ is automatically expanded)') do |path|
    options[:cache_path] = path.sub('~', '#{Dir.home}')
  end
end

option_parser.parse!

case ARGV.length
when 1 # Configuration file passed
  config_file = ARGV[0]
  require config_file

  puts Heroics.generate_client
when 3 # Traditional module name, schema and base URL params passed
  module_name, schema_filepath, base_url = ARGV

  Heroics.default_configuration do |config|
    config.module_name = module_name
    config.schema_filepath = schema_filepath

    config.base_url = base_url

    if options[:cache_path]
      config.cache_path = options[:cache_path]
    end

    if options[:headers]
      config.headers = options[:headers]
    end
  end

  puts Heroics.generate_client
else # incorrect or no CLI params, show help
  puts option_parser
end
