#!/usr/bin/env jruby
=begin
JRubyFX - Write JavaFX and FXML in Ruby
Copyright (C) 2013 The JRubyFX Team

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end

require 'date'
require 'jrubyfx/utils'
require 'pathname'

if ARGV.length < 1
  puts "Please specify the fxml file to parse"
  puts "#{$0} some.fxml [output.rb [AppName]]"
  exit -1
end

fxml = ARGV[0]
rb = File.basename(fxml.gsub(/\.fxml$/i, ".rb"))
rb = ARGV[1] if ARGV.length > 1
name_guess = "My" + File.basename(fxml).gsub(/\.fxml$/i, "").gsub(/[^a-zA-Z0-9_]/i, "") # better guess would be better
name_guess = ARGV[2] if ARGV.length > 2

print "Generating JRubyFX template for #{fxml} into #{rb}... "

File.open(rb, "w") do |output|

  fx_diff_root = ("/" + Pathname.new(File.dirname fxml).relative_path_from(Pathname.new(File.dirname rb)).to_s).inspect
  fx_diff_root = if fx_diff_root == '"/."'
    ""
  else
    " + #{fx_diff_root}"
  end
  output << <<END
# This file was auto-generated by jrubyfx-generator at #{DateTime.now.to_s}

require 'jrubyfx'
fxml_root File.dirname(__FILE__)#{fx_diff_root}

class #{name_guess}Application < JRubyFX::Application
  def start(stage)
    with(stage, title: "#{name_guess}") do
      fxml #{name_guess}Controller
      show
    end
  end
end

class #{name_guess}Controller
  include JRubyFX::Controller
  fxml "#{File.basename(fxml)}"
END

  fx_ids = []
  File.open(fxml, "r") do |fx|
    handlers = "\n"

    fx.each_line do |line|
      line.scan(/fx:id="([^ "':]+)"/) do |match|
        fx_ids << match[0]
      end
      # TODO: may not work with funky non-latin characters
      # Yes, I used regex, yes its xml, yes I now have two problems.
      line.scan(/on((([A-Z]*[a-z]*)*?)[A-Z]+[a-z]+)="#([^ "':]+)"/) do |match|
        handlers << "  def #{match[3]}(event)\n"
        handlers << "    # TODO: Auto-generated event handler\n"
        handlers << "    puts \"#{match[0]} event '#{match[3]}' called\"\n  end\n\n"
      end
    end
    output << "\n  # nodes with ruby method-like fx:ids may be accessed directly"
    output << "\n  def initialize\n#{fx_ids.map{|x|"    puts \"fx:id=\\\"#{x}\\\" was not injected: check your FXML file '#{File.basename(fxml)}'.\" unless @#{x}"}.join "\n"}\n  end\n"
    output << handlers
  end

  output << <<END
end

#{name_guess}Application.launch
END

end

puts "Done!"

puts "Launching 'jruby #{rb}' ..."

require rb