#!/usr/bin/ruby


if (ARGV.length == 0) 

	print ("internal error - insufficient arguments");
	exit 1
end

#require ARGV[0]+"/extract_options.rb"
require ARGV[0]+"/SQLEditorActiveRecord3.rb"
#require ARGV[0]+"/SQLTable.rb"

# for logging
class StdOutLogger
	
	def initialize
	
		@outputString = ""
	end

	def write(s)
		@outputString += s
	end
	
	def to_s
	
		return @outputString
	end
end


if (ARGV.length >= 2) 
  #STDERR.print "using ARV"
  originalFileName = ARGV[1]

  
end

if (originalFileName.tainted?) 

	fileName = String.new(originalFileName)
	fileName.untaint
end


#require 'open-uri'
#
#f = open("http://localhost/")
#
#print f.read


$stdout_default = $stdout.clone



# level 3 is about as high as we can go, it should disallow file
# operations (mostly) - note: add a warning in the manual about this
#$SAFE=3


Kernel.load(fileName,false)
className = ""
if (ARGV.length >= 4)

	className = ARGV[3]
else 
	
	Module.constants.each { |constantName|
		
		currentClass = Kernel.const_get(constantName)
		
		if (currentClass.class == Class.class) 
			
			if (currentClass.superclass == ActiveRecord::Migration) 
				className = currentClass.to_s
				end
			
			end
		
	}
end


# redirect the standard output to a special logging system
$stdout_default = $stdout.clone
$stdout_logger = StdOutLogger.new
$stdout = $stdout_logger
begin

	
	errorResult = ""
	xmlResult = ""
    
    if (className != "") 
        #STDERR.print("classname = "+className.to_s+"\n");
        print "<!-- class name = "+className+" "+Kernel.const_get(className).to_s+" -->\n"
    else
        print "<!-- schema define -->\n"
    end
    print "\n"
    

    
    
    
    

    
    
    print "\n"
    
	print "<SQLContainer>\n"
	

	
	#targetObject = Kernel.const_get(className);
	
	if (className != "") 
		if (Kernel.const_get(className).respond_to?('up')) 
			print "<!--migration found -->\n";
			Kernel.const_get(className).up
		end
        
        
        
        if (Kernel.const_get(className).respond_to?('change'))
			print "<!--migration found (change style) -->\n";
			Kernel.const_get(className).change
		end
        
        
        migrationInstance = Kernel.const_get(className).new
        
        if (migrationInstance.respond_to?('change'))
            print "<!--migration found (change style 2) -->\n";

            migrationInstance.change
        end
        
	else 
		print "<!--schema found -->\n";
		
		# note that we don't need to call up because the define was already called in the schema file
		# when the class was loaded
	end

	#print  "\nTableList = "
	
	#print "\n "+ActiveRecord::Migration.tableList.to_s()
	
	#print "==\n"
	
	ActiveRecord::Migration.tableList.each  do |item|
	
		print "\n"+item.to_xml() + "\n"
	end
	
	print  "\n"
	print "</SQLContainer>\n"

	# format is specific to match plist format (mac os x)

	rescue Exception => securityError
		errorResult += "<dict>"
		errorResult += "<key>message</key>\n"
		errorResult += "<string><![CDATA[" + securityError.message + "]]></string>\n"
		
		errorResult += "<key>backtrace</key>\n"
		errorResult += "<string><![CDATA[" + securityError.backtrace.first.to_s + "]]></string>\n"
		errorResult += "</dict>"
	ensure 
	
	
	
	
	$stdout = $stdout_default
	


end


# now display the result 

	STDOUT.print "<SQLEditorPluginResult>\n"
	STDOUT.print "<SQLEditorErrorStatus>\n"
	if (errorResult != "") 
		STDOUT.print '<?xml version="1.0" encoding="UTF-8"?>' + "\n"
		
		STDOUT.print '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' + "\n"
		STDOUT.print '<plist version="1.0">' + "\n"
		STDOUT.print '<array>'
		STDOUT.print errorResult
		STDOUT.print '</array>'
		STDOUT.print '</plist>'
	end
	STDOUT.print "<SQLEditorErrorStatus>\n"
	
	STDOUT.print "<SQLEditorDocument>\n"
	STDOUT.print $stdout_logger
	STDOUT.print "</SQLEditorDocument>\n"




