require 'rubygems'

load File.join(File.dirname(__FILE__), "buildwise.rake")

# BUILDWISE_QUICK_PROJECT_ID = "agiletravel-quick-build-mocha" 
BUILDWISE_FULL_PROJECT_ID = "agiletravel-full-build-mocha"
BUILDWISE_URL = ENV["BUILDWISE_MASTER"] || "http://buildwise.macmini"

FULL_BUILD_MAX_TIME = 60 * 60   # 1 hour
FULL_BUILD_CHECK_INTERVAL = 30  # 1 minute

$test_dir = File.join(File.join(File.dirname(__FILE__), "spec"))


# list of specs for quick build under $test_dir.
# instead of list one by one, you may change to include all in $test_dir, which is the way for parallel build
def specs_for_quick_build 
  [
    "01_login_spec.js",
    "02_flight_spec.js",
    "03_passenger_spec.js",
    "04_payment_spec.js",
    "not_exists_spec.js"
  ]
end


def excluded_spec_files
  # ["ignore_spec.rb", "bad_test.rb", "selected_scripts_spec.rb"]
  ["ignored_spec.js", "03_passenger_spec.js"]
end

desc "run all tests in this folder"
task "ui_tests:quick"  do
  `cd selenium-webdriver-nodejs-mocha; mocha spec --reporter mocha-junit-reporter`
end

def determine_specs_for_quick_build
  specs_to_be_executed = []

  enable_intelligent_ordering = ENV["INTELLIGENT_ORDERING"] && ENV["INTELLIGENT_ORDERING"].to_s == "true"
  puts "[INFO] intelligent ordering? => #{enable_intelligent_ordering.to_s rescue 'false'}"
  if enable_intelligent_ordering && ENV["BUILDWISE_PROJECT_IDENTIFIER"]
    ordered_specs = buildwise_ui_test_order(ENV["BUILDWISE_PROJECT_IDENTIFIER"])
    puts "[INFO] Execution order based history of quick build: #{ordered_specs.inspect}"
    if ordered_specs.nil? || ordered_specs.compact.empty? || ordered_specs.class != Array
      specs_to_be_executed += specs_for_quick_build  if specs_to_be_executed.empty?
    else
      # neat sorting thanks to Ruby
      specs_to_be_executed = ordered_specs.dup
      specs_to_be_executed = specs_to_be_executed.sort_by{|x| ordered_specs.include?(File.basename(x)) ? ordered_specs.index(File.basename(x)) : specs_to_be_executed.count }    
      puts "[INFO] After intelligent sorting => #{specs_to_be_executed.inspect}"        
    end    
  end
  
  enable_dyanmic_build_queue = ENV["DYNAMIC_FEEDBACK"] && ENV["DYNAMIC_FEEDBACK"].to_s == "true" && ENV["DYNAMIC_FEEDBACK_PROJECT_IDENTIFIER"]
  puts "[INFO] dynamic feedback? => #{enable_dyanmic_build_queue}"  
  if enable_dyanmic_build_queue
    begin
      # dynamic build process: get failed tests from last failed full build
      failed_full_build_tests = buildwise_failed_build_tests(ENV["DYNAMIC_FEEDBACK_PROJECT_IDENTIFIER"])
      if failed_full_build_tests && failed_full_build_tests.size > 0
        failed_full_build_tests.each do |x|
          full_path = File.join($spec_dir, x)
          specs_to_be_executed.insert(0, full_path) unless specs_to_be_executed.include?(full_path)
        end    
      end
    
    rescue => e
      puts "[ERROR] failed to check for full build: #{e}"
    end
  end

  if specs_to_be_executed.empty?
    specs_to_be_executed = specs_for_quick_build
  else
    specs_left_over = specs_for_quick_build - specs_to_be_executed
    specs_to_be_executed += specs_left_over
    specs_to_be_executed.flatten!    
  end
  
  specs_to_be_executed -= excluded_spec_files
  specs_to_be_executed.uniq!
  puts "[INFO] Uniq : #{specs_to_be_executed.inspect}"

  specs_to_be_executed.reject! {|a_test|  !File.exist?(File.join($test_dir, a_test)) }
  puts "[INFO] Filter Not exists : #{specs_to_be_executed.inspect}"

  puts "[INFO] Final Test execution in order => #{specs_to_be_executed.inspect}"
  # using full path
  specs_to_be_executed = specs_to_be_executed.collect{|x| File.join($test_dir, x)}  
end


desc "run all tests in this folder"
task "ci:ui_tests:quick" do
    reports_dir = File.join(File.dirname(__FILE__),  "reports")
    FileUtils.rm_rf(reports_dir) if File.exist?(reports_dir)
    FileUtils.mkdir_p(reports_dir)
    
    exit_code = 0    

    specs_to_be_executed = determine_specs_for_quick_build();
    specs_to_be_executed.each do |test_file|
      result_file =  File.basename(test_file).gsub(".js", ".xml")      
      cmd = "./node_modules/jasmine-xml-reporter/bin/jasmine.js #{test_file} --junitreport --output=results --filePrefix=#{result_file}"
      puts cmd
      result = system(cmd)
      if exit_code == 0 && !result
        exit_code = -1
      end   
      sleep 0.25
    end
    exit(exit_code)  
end



## Full Build
#
#  TODO - how to determin useing RSpec or Cucumber
#
desc "Running tests in parallel"
task "ci:ui_tests:full" do
  build_id = buildwise_start_build(:working_dir => File.expand_path(File.dirname(__FILE__)),
                                   :ui_test_dir => ["spec"],
                                   :excluded => excluded_spec_files || [],
                                   :parallel => true,
                                   :test_framework => "Mocha"
  )

  buildwise_montior_parallel_execution(build_id, :max_wait_time => FULL_BUILD_MAX_TIME, :check_interval => FULL_BUILD_CHECK_INTERVAL)  
end
