# You need Ruby (Rake, ci_reporter gems installed)

require 'rubygems'
gem 'ci_reporter'
gem 'rspec'
require 'rspec/core/rake_task'
require 'ci/reporter/rake/rspec' # use this if you're using RSpec

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

## Settings: Customize here...
# 
BUILDWISE_URL = ENV["BUILDWISE_MASTER"] || "http://buildwise.dev"
# BUILDWISE_QUICK_PROJECT_ID = "agiletravel-quick-build-rspec"
# BUILDWISE_FULL_PROJECT_ID  = "agiletravel-full-build-rspec" # import to set for full build
 
FULL_BUILD_MAX_TIME = ENV["DISTRIBUTED_MAX_BUILD_TIME"].to_i || 60 * 60   # max build time, over this, time out
FULL_BUILD_CHECK_INTERVAL =  ENV["DISTRIBUTED_BUILD_CHECK_INTERVAL"].to_i || 20  # check interval for build complete

$test_dir =  File.expand_path( File.join( File.dirname(__FILE__), "test" ) )  # change to aboslution path if invocation is not this directory
# rspec will create 'spec/reports' under check out dir

# List tests you want to exclude
#
def excluded_spec_files
  # NOTE, testing only for faster develping agent, remove a couple of test later
  ["selected_scripts_test.py", "03_passenger_test.py"]
end

def all_specs
  Dir.glob("#{$test_dir}/*_test.py")
end

def specs_for_quick_build
  # list test files to be run in a quick build, leave the caller to set full path
  [
    "1_login_test.py", 
    "2_flight_test.py",
    "3_passenger_test.py",
    "4_payment_test.py",
	"new_test.py",
    "not_exists_test.py" # test handling non exists scenario
  ]
end


desc "run tests in this spec/ folder, option to use INTELLIGENT_ORDERING or/and DYNAMIC_FEEDBACK"
RSpec::Core::RakeTask.new("ui_tests:quick") do |t|  
  specs_to_be_executed = buildwise_determine_specs_for_quick_build(specs_for_quick_build, excluded_spec_files, $test_dir);
  buildwise_formatter =  File.join(File.dirname(__FILE__), "buildwise_rspec_formatter.rb")
  t.rspec_opts = "--pattern my_own_custom_order --require #{buildwise_formatter} #{specs_to_be_executed.join(' ')} --order defined"
end


desc "run quick tests from BuildWise"
task "ci:ui_tests:quick" => ["ci:setup:rspec"] do
  build_id = buildwise_start_build(:working_dir => File.expand_path(File.dirname(__FILE__)))
  buildwise_run_sequential_build_target(build_id, "ui_tests:quick")
end


## Full Build
#
desc "Running tests distributedly"
task "ci:ui_tests:full" => ["ci:setup:rspec"] do
  build_id = buildwise_start_build(:working_dir => File.expand_path(File.dirname(__FILE__)),
                                   :ui_test_dir => ["spec"],
                                   :excluded => excluded_spec_files || [],
                                   :parallel => true
  )
  buildwise_montior_parallel_execution(build_id, :max_wait_time => FULL_BUILD_MAX_TIME, :check_interval => FULL_BUILD_CHECK_INTERVAL)
end


desc "run all tests in this folder"
RSpec::Core::RakeTask.new("go") do |t|
  test_files = Dir.glob("*_test.py") + Dir.glob("*_test.rb") - excluded_test_files
  t.pattern = FileList[test_files]
  t.rspec_opts = "" # to enable warning: "-w"
end


desc "Generate stats for UI tests"
task "test:stats" do

  ui_test_dir = File.dirname(__FILE__)
  STATS_SOURCES = {
      "Tests" => "#{ui_test_dir}/test",
      "Pages" => "#{ui_test_dir}/pages",
      "Helpers" => "#{ui_test_dir}/*_helper.py",
  }

  test_stats = {"lines" => 0, "test_suites" => 0, "test_cases" => 0, "test_lines" => 0}
  page_stats = {"lines" => 0, "classes" => 0, "methods" => 0, "code_lines" => 0}
  helper_stats ={"lines" => 0, "helpers" => 0, "methods" => 0, "code_lines" => 0}

  # Tests
  directory = STATS_SOURCES["Tests"]
  Dir.foreach(directory) do |file_name|
    next if file_name == "." || file_name == ".." || file_name == "selected_scripts_test.py"
    next if File.directory?(File.join(directory, file_name))
    f = File.open(directory + "/" + file_name)
    test_stats["test_suites"] += 1
    while line = f.gets
      test_stats["lines"] += 1
      test_stats["test_cases"] += 1 if line =~ /^\sdef test_/
      test_stats["test_lines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
    end
    f.close
  end
  # puts test_stats.inspect

  # Pages
  directory = STATS_SOURCES["Pages"]
  Dir.foreach(directory) do |file_name|
    next if file_name == "." || file_name == ".."
    f = File.open(directory + "/" + file_name)
    while line = f.gets
      page_stats["lines"] += 1
      page_stats["classes"] += 1 if line =~ /class [A-Z]/
      page_stats["methods"] += 1 if line =~ /def [a-z]/
      page_stats["code_lines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
    end
    f.close
  end

  # Helpers
  # directory = File.dirname( STATS_SOURCES["Helpers"])
  # helper_wildcard = File.basename( STATS_SOURCES["Helpers"])
  # puts directory
  # puts helper_wildcard
  Dir.glob(STATS_SOURCES["Helpers"]).each do |helper_file|
    f = File.open(helper_file)
    helper_stats["helpers"] += 1
    while line = f.gets
      helper_stats["lines"] += 1
      helper_stats["methods"] += 1 if line =~ /def [a-z]/
      helper_stats["code_lines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
    end
    f.close
  end

  total_lines = helper_stats["lines"] + page_stats["lines"] + test_stats["lines"]
  total_code_lines = helper_stats["code_lines"] + page_stats["code_lines"] + test_stats["test_lines"]

  puts "+------------+---------+---------+---------+--------+"
  puts "| TEST       |   LINES |  SUITES |   CASES |    LOC |"
  puts "|            | #{test_stats['lines'].to_s.rjust(7)} " + "| #{test_stats['test_suites'].to_s.rjust(7)} " + "| #{test_stats['test_cases'].to_s.rjust(7)} " + "| #{test_stats['test_lines'].to_s.rjust(6)} " + "|"
  puts "+------------+---------+---------+---------+--------+"
  puts "| PAGE       |   LINES | CLASSES | METHODS |    LOC |"
  puts "|            | #{page_stats['lines'].to_s.rjust(7)} " + "| #{page_stats['classes'].to_s.rjust(7)} " + "| #{page_stats['methods'].to_s.rjust(7)} " + "| #{page_stats['code_lines'].to_s.rjust(6)} " + "|"
  puts "+------------+---------+---------+---------+--------+"
  puts "| HELPER     |   LINES |   COUNT | METHODS |    LOC |"
  puts "|            | #{helper_stats['lines'].to_s.rjust(7)} " + "| #{helper_stats['helpers'].to_s.rjust(7)} " + "| #{helper_stats['methods'].to_s.rjust(7)} " + "| #{helper_stats['code_lines'].to_s.rjust(6)} " + "|"
  puts "+------------+---------+---------+---------+--------+"
  puts "| TOTAL      | " + total_lines.to_s.rjust(7) + " |         |         |" + total_code_lines.to_s.rjust(7) + " |"
  puts "+------------+---------+---------+---------+--------+"

end
