#!/usr/bin/env ruby

require 'fssm'
require 'colorize'
require 'optparse'

def log msg
  puts msg.colorize :light_blue
end

def spec filepath
  spec_filepath = File.join $opts[:root_path], filepath
  cmd = "cd \"#{$opts[:root_path]}\"; rspec -I spec --color --format doc \"#{spec_filepath}\" --tag ~speed:slow"
  cmd << " --example \"#{$opts[:example]}\"" if $opts[:example]
  start = Time.now
  puts "Running #{filepath}..."
  result = system(cmd)
end

def integration_spec(path)
  Dir[]
end

def changed filepath
  can_run = !$opts[:regexp] || ($opts[:regexp] && Regexp.new($opts[:regexp]).match(filepath))

  return unless can_run

  log "The file #{filepath} has changed!"

  if filepath =~ /.*_spec.rb/
    spec filepath
  else
    spec_filepath = "spec/" + filepath.gsub('.rb', '_spec.rb')

    if File.exists?(spec_filepath)
      spec(spec_filepath)
    elsif $opts[:regexp]
      Dir["spec/integration/**/*#{$opts[:regexp]}*_spec.rb"].each { |path| spec(path) }
    end
  end
end

def monitor path, opts = {}
  log "Watching for changes #{path}..."
  FSSM.monitor(path, '**/*.rb') do
    update { |f, r| changed(r) }
  end
end

$opts = {}
$opts[:root_path] = File.expand_path(File.join(File.dirname(__FILE__), '..'))

OptionParser.new do |opts|
  opts.on( '-f', '--file REGEXP', String, 'Consider only files that matches REGEXP' ) { |value| $opts[:regexp] = value }
  opts.on( '-e', '--example REGEXP', String, 'Consider only examples that matches REGEXP' ) { |value| $opts[:example] = value }
  opts.on( '-r', '--root-path [PATH]', String, "Root path. Default is #{$opts[:root_path]}") { |value| $opts[:root_path] = value }
end.parse!

puts "Options: " + $opts.inspect

monitor($opts[:root_path])
