require 'json'
require 'net/http'
require 'net/https'
require 'uri'
require './core/api/external_api'

# Ruby 1.9 HTTP Response Info: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

# rubocop:disable Style/AlignParameters

exit(0) unless ENV['NOTIFICATIONS'] && ENV['NOTIFICATIONS'].downcase == 'true' # Exit if notification not requested

# Authentication
if ENV['JENKINS_USERNAME'] && ENV['JENKINS_TOKEN'] && ENV['SLACK_TOKEN'] && ENV['BUILD_NUMBER'] && ENV['JOB_NAME']
  @jenkins_username = ENV['JENKINS_USERNAME']
  @jenkins_token = ENV['JENKINS_TOKEN']
  @slack_token = ENV['SLACK_TOKEN']
  @build_number = ENV['BUILD_NUMBER']
  job_name = ENV['JOB_NAME']
else
  raise Exception.new('Must provide these ENV Variables: JENKINS_USERNAME, JENKINS_TOKEN, SLACK_TOKEN, BUILD_URL')
end

include ExternalAPI::Notifications::Slack

@automation_room = '#qa-automation'

# Grab Build Data from Jenkins
uri = "https://smoca.internal.justin.tv/api/jenkins_build/#{job_name}/#{@build_number}"
build_response = rest_get(uri, true, false)

x = 1
while (build_response.code != '200') && (x <= 5)
  sleep(10) # Retry every 10 seconds
  puts "WARN: Encountered a response code #{build_response.code}. Retry \##{x}..."
  build_response = rest_get(uri, true, false)
  x += 1
end

if build_response.code == '200'
  build = JSON.parse(build_response.body)
else
  error = "ERROR: Encountered an error making a GET #{uri}. Received response: #{build_response.code}. Build \##{@build_number}"
  send_slack_message('smoca-monitoring', '', error) # Notify slack channel of the error
  raise Exception.new(error)
end

# Obtain Slack User Information
# Note: ENV['SLACK_USER_OVERRIDE'], if it exists, will override initiator user name
slack_user = get_slack_user(ENV['SLACK_USER_OVERRIDE'] || build['initiatedBy'], ENV['SLACK_USER_OVERRIDE'] ? true : build['ldap'])

if slack_user.nil?
  raise "Unable to find Slack user #{ENV['SLACK_USER_OVERRIDE'] || build['initiatedBy']}"
end

slack_id = slack_user[:id]

if slack_id != nil
  # Slack ID will be false if it was overridden not to be used.
  # Purpose is for auto deploy bots that don't have a Slack ID
  if slack_id != false
    # It's a real user, so send it to them via DM
    message_text = 'Attached are your Smoca results!'
    if build['results'] == 'FAILURE'
      message_text += "\nGo to #smoca-support for troubleshooting assistance!"
    end

    send_slack_message(open_dm(slack_id), construct_attachments(build), message_text) # Opens DM and Sends Slack Message
  end

  send_slack_message('smoca-monitoring', construct_attachments(build), false) # Send results to a group Slack channel in addition
else
  send_slack_message(@automation_room, construct_attachments(build), "_Unable to find the initiator on Slack._\n")
  raise Exception.new('Unable to find the initiator on Slack.')
end
