#!/usr/local/bin/ruby

#
# modeler - creating model files for TapKit
#
# usage:
#   modeler [-h|--help] adapter filename
#
# exmaple:
#  % ./modeler DBI test.yaml

$LOAD_PATH.unshift '../lib'

require 'tapkit'
require 'yaml'

class Modeler
	include TapKit

	USAGE = "usage: modeler [-h|--help] adapter filename"
	HELP = "options:\n" +
	"    -h, --help      show help (this message)\n"


	def initialize( args )
		if args.include?('-h') or args.include?('--help') then
			show_help
			exit
		elsif args.empty? then
			show_usage
			exit
		end

		@filename = args.pop
		@adapter_name = args.pop
	end

	def show_usage
		puts USAGE
	end

	def show_help
		show_usage
		puts
		puts HELP
	end

	# 1. after running modeler command with adapter name, show login prompt
	#    with runing the adapter's run_login_prompt().
	#    The method runs a login prompt using with Adapter.login_prompt().
	# 2. the prompt returns connection infomation, sets to the adapter.
	# 3. shows all selectable tables by describe_table_names() and
	#    requires selecting table names.
	# 3. creates a model object with running the describe_model().
	# 4. parses the model and creates relationships.
	# 5. creates a model file.
	def run
		adapter = Adapter.new_with_name @adapter_name

		unless connection = adapter.run_login_prompt then
			puts "connection failed"
			exit
		end
		
		adapter.connection = connection
		context = adapter.create_context
		channel = context.create_channel

		tables = select_tables channel
		model = channel.describe_model tables
		model.parse_relationships

		yaml = model.to_yaml
		open(@filename, 'w') do |f|
			f.write yaml
		end
		puts "Create #@filename"
	end

	def select_tables( channel )
		tables = channel.describe_table_names
		unless tables.empty? then
			puts "Selectable tables - #{tables.join(', ')}"
			puts "(If you want to select the all tables, input 'all')"
		end

		selected = nil
		while true
			print "Select tables (separate table names with comma): "
			table_str = gets.chomp
			table_str.strip!

			if table_str == 'all' then
				selected = tables
			else
				selected = table_str.split ','
			end

			unless table_str.empty? then
				break
			end
		end

		selected
	end
end


if __FILE__ == $0 then
	modeler = Modeler.new ARGV
	modeler.run
end
