# Encoding: utf-8
require 'rubygems'
require 'cucumber'
require 'cucumber/rake/task'
require 'rubocop/rake_task'

$LOAD_PATH.push(File.expand_path(File.dirname(__FILE__) + '/features/pageobject_dir'))

# Check environment sanity and fail fast if not correct
fail 'WORKSPACE environment variable not set. Did you "source infrastructure/set.env.sh"?' unless ENV.keys.include?('WORKSPACE')
fail 'GEM_HOME environment variable not set. Did you "source infrastructure/set.env.sh"?' unless ENV.keys.include?('GEM_HOME')

task default: [:endToEndTests]

task endToEndTests: [:codequality]
task endToEndStableTests: [:codequality]
task endToEndUnstableTests: [:codequality]

task codequality: [
  :info,
  :rubocop
]

task baseTests: [:smokeTests]
task recentTests: [:smokeTests]
task regressionTests: [:smokeTests]
task failingTests: [:smokeTests]

task :endToEndTests, [:env] => [:environment_setup]
task :endToEndStableTests, [:env] => [:environment_setup]
task :endToEndUnstableTests, [:env] => [:environment_setup]
task :endToEndOncTests, [:env] => [:environment_setup]
task :recentTests, [:env] => [:environment_setup]
task :baseTests, [:env] => [:environment_setup]
task :regressionTests, [:env] => [:environment_setup]
task :smokeTests, [:env] => [:environment_setup]
task :failingTests, [:env] => [:environment_setup]

def browser_setup(btype)
  case btype.downcase
  when "phantomjs"
    puts "PHANTOMJS selected"
  when "firefox"
    puts "FIREFOX selected"
  when "SAFARI"
    puts "SAFARI selected"
  when "IE"
    puts "IE selected"
  when "chrome"
    puts "Chrome selected"
  else
    fail "Unrecognized browser type: #{btype}. Allowable types are: 'PHANTOMJS', 'FIREFOX', 'CHROME', 'SAFARI', and 'IE'"
  end
end

def create_or_clear_screenshots_folder
  ENV["SCREENSHOTS_FOLDER"] = "screenshots"
  FileUtils.rm_rf Dir.glob("#{ENV["SCREENSHOTS_FOLDER"]}/*.png")
  #Dir.mkdir(ENV["SCREENSHOTS_FOLDER"])
end

## Attempting to run a sample acceptance test in the features directory
Cucumber::Rake::Task.new(:endToEndTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'phantomjs'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

## Attempting to run a sample acceptance test in the features directory
Cucumber::Rake::Task.new(:endToEndStableTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags ~@onc --tags ~@unstable --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

Cucumber::Rake::Task.new(:endToEndOncTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags @onc --tags ~@unstable --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

Cucumber::Rake::Task.new(:smokeTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags @smoke --tags ~@unstable --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

Cucumber::Rake::Task.new(:regressionTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags @regression --tags ~@triage --tags ~@unstable --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

Cucumber::Rake::Task.new(:baseTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags @base --tags ~@unstable --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

Cucumber::Rake::Task.new(:recentTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags ~@smoke --tags ~@base --tags ~@regression --tags ~@onc --tags ~@unstable --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

Cucumber::Rake::Task.new(:failingTests) do |t|
  p 'running end to end'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  browser_setup(btype)
  t.cucumber_opts = 'features --format pretty --tags @triage --tags ~@onc --tags ~@unstable --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype
end

## Placeholder task for executing all Acceptance Tests for all Mobile Applications
Cucumber::Rake::Task.new(:allAcceptanceTests) do |t|
  create_or_clear_screenshots_folder
  p 'running all acc tests'
  btype = ENV['BTYPE'] || 'PHANTOMJS'
  #t.cucumber_opts = 'features --format pretty BROWSERTYPE=' << btype
  t.cucumber_opts = 'features --format pretty --tags ~@future --tags ~@debug --tags ~@manual -f json_pretty -o cucumber.json -f html -o cucumber.html --color BROWSERTYPE=' << btype

end

task :info do
  puts '=========================================================================='
  puts '#     Running codequality checks.                                        #'
  puts '#     For details, see https://wiki.vistacore.us/display/VACORE/Ruby     #'
  puts '=========================================================================='
end

desc 'Rubocop code quality checks configured in .rubocop.yml file'
Rubocop::RakeTask.new(:rubocop) do |rubocop|
  # Specify config file in non-standard location.
  rubocop.options = ['-c.rubocop.yml']

  # Specify Ruby file locations
  rubocop.patterns = ['**/*.rb', 'Rakefile']

  # Show emacs style output, and offense counts
  # See https://github.com/bbatsov/rubocop#formatters for other output options
  rubocop.formatters = ['emacs', 'o']

  # Abort rake on failure
  rubocop.fail_on_error = true
end

task :environment_setup, :env do |task, args|
  env = args[:env] || 'virtualbox'
  environment_endpoints(env)
end

def environment_endpoints(env)
  case env
  when "virtualbox"
    ip = knife_search_for_ip("ehmp-ui")
    ENV["EHMPUI_IP"] = 'https://' + "#{ip}"
    ENV["LOCAL"] = "true"
  when "aws"
    ip = knife_search_for_ip("ehmp-balancer")
    ENV["EHMPUI_IP"] = 'https://' + "#{ip}"
    p "env #{ENV["EHMPUI_IP"]}"
  else
    fail "Unrecognized environment type: #{env}. Allowable types are: 'virtualbox' and 'aws'"
  end
end

def knife_search_for_ip(machine_name)
  release = File.read(File.dirname(__FILE__) + "/../../../infrastructure/properties/releaseVersion")
  stack = ENV['JOB_NAME'] || "#{ENV['USER']}-#{release}"
  if ENV.key?('BUNDLE_BIN_PATH')
    raw_search = Bundler.with_clean_env { `/opt/chefdk/bin/knife search node \'role:#{machine_name} AND stack:#{stack}\' -Fj --config ~/Projects/vistacore/.chef/knife.rb` }
  else
    raw_search = `/opt/chefdk/bin/knife search node \'role:#{machine_name} AND stack:#{stack}\' -Fj --config ~/Projects/vistacore/.chef/knife.rb`
  end
  parsed_search = JSON.parse(raw_search)
  fail "More than one node with that name found" if parsed_search["results"] > 1
  fail "No node with that name found: \'role:#{machine_name} AND stack:#{stack}\'" if parsed_search["results"] == 0
  ip = parsed_search["rows"][0]['automatic']['ipaddress']
end
