#!/usr/bin/env ruby

require 'rubygems'

gem_dir = File.expand_path('../..', __FILE__)
$:.unshift(File.join(gem_dir, 'lib'))

require 'yaml'
require 'fileutils'
require 'getoptlong'

gem 'jasmine'
gem 'coffee-script'
gem 'rainbow'

require 'jasmine'
require 'coffee-script'
require 'rainbow'

require 'jasmine/cli'
include Jasmine::CLI

opts = GetoptLong.new(
  [ '--colors', '-c', GetoptLong::NO_ARGUMENT ],
  [ '--no-colors', GetoptLong::NO_ARGUMENT ],
  [ '--keep', GetoptLong::NO_ARGUMENT ]
)

options = { :colors => false, :remove_html_file => true }

@process_options = lambda { |*args|
  opt = args.flatten.shift
  case opt
  when '--colors', '-c'
    options[:colors] = true
  when '--no-colors', '-nc'
    options[:colors] = false
  when '--keep', '-k'
    options[:remove_html_file] = false
  end
}

read_defaults_file if defaults_file?
opts.each(&@process_options)

data = YAML.load_file(ARGV.shift || 'spec/javascripts/support/jasmine.yml')

if !File.file?(File.join(gem_dir, RUNNER))
  puts "The Qt WebKit widget is not compiled! Try re-installing this gem."
  exit 1
end

puts "Running Jasmine specs..."

files = %w{jasmine jasmine-html}.collect { |name| File.join(Jasmine.root, "lib/#{name}.js") }

files += [ [ 'src_files', 'src_dir' ], [ 'stylesheets', 'src_dir' ], [ 'helpers', 'spec_dir' ], [ 'spec_files', 'spec_dir' ] ].collect do |searches, root|
  data[searches] ||= DEFAULTS[searches]
  data[root] ||= DEFAULTS[root]

  if data[searches]
    data[searches].collect do |search|
      path = search
      path = File.join(data[root], path) if data[root]
      Dir[path]
    end
  end
end

files = files.flatten.compact.collect { |file|
  case File.extname(file)
  when '.js'
    %{<script type="text/javascript" src="#{file}"></script>}
  when '.coffee'
    begin
      %{<script type="text/javascript">#{CoffeeScript.compile(fh = File.open(file))}</script>}
    rescue CoffeeScript::CompilationError => e
      puts "[%s] %s: %s" % [ 'coffeescript'.color(:red), file.color(:yellow), e.message.color(:white) ]
      exit 1
    ensure
      fh.close
    end
  when '.css'
    %{<link rel="stylesheet" href="#{file}" type="text/css" />}
  end
}

output = jasmine_html_template(files)

File.open(target = "specrunner.#{$$}.html", 'w') { |fh| fh.print output }
system %{#{File.join(gem_dir, RUNNER)} #{options[:colors] ? '-c' : ''} #{target}}
status = $?.exitstatus
FileUtils.rm_f target if options[:remove_html_file] || (status == 0)

exit status