require 'httparty'

@root_endpoint = 'http://qe-heimdall.us-west2.justin.tv'

def add_usertype_heimdall(usertype, description)
  endpoint = "#{@root_endpoint}/types"
  body_params = {name: usertype, description: description}
  response = HTTParty.post(endpoint, body: body_params)

  if response.code == 201
    puts "Added #{usertype} - #{description}. Body: #{response.body}"
  else
    raise "Encountered unexpected response code: #{response.code} - Body: #{response.body}"
  end
end

def add_username_heimdall(usertype, username)
  endpoint = "#{@root_endpoint}/types/#{usertype}/users"
  body_params = {username: username}
  response = HTTParty.post(endpoint, body: body_params)

  if response.code == 201
    puts "Added username #{username} to type #{usertype}"
    puts "Body: #{response.body}"
  else
    raise "Encountered unexpected response code: #{response.code} - Body: #{response.body}"
  end
end

def lock_user(usertype, username, env='staging')
  endpoint = "#{@root_endpoint}/types/#{usertype}/users/#{username}/#{env}/lock"
  r = HTTParty.put(endpoint)

  if r.code == 200
    puts "Successfully locked #{usertype}/#{username} on staging"
  else
    raise "Unexpected response. #{r.code} - body: #{r.body}"
  end
end

def add_user_flow
  if @inputted_user_type
    print "Would you like to add a username to type #{@inputted_user_type}? (y/n) "
    if gets.chomp.downcase == 'y'
      user_type = @inputted_user_type
    else
      print 'What UserType would you like to add a username to: '
      user_type = gets.chomp.downcase
    end
  else
    print 'What UserType would you like to add a username to: '
    user_type = gets.chomp.downcase
  end

  print "Enter the username you would like to add to type #{user_type}: "
  username = gets.chomp.downcase
  add_username_heimdall(user_type, username)

  print "Would you like to lock #{username} on staging? (y/n) "
  staging_lock = (gets.chomp.downcase == 'y')

  lock_user(user_type, username) if staging_lock
end

def add_usertype_flow
  print 'Enter the User Type to add: '
  @inputted_user_type = gets.chomp.downcase

  print "Enter a description to store for '#{@inputted_user_type}': "
  description = gets.chomp.downcase

  add_usertype_heimdall(@inputted_user_type, description)
end

@inputted_user_type = nil

print 'Are you looking to add a new User Type? (y/n) '
if gets.chomp.downcase == 'y'
  add_usertype_flow
end


print 'Are you looking to add a new User Name? (y/n) '
add_users = gets.chomp.downcase == 'y'
while add_users
  add_user_flow
  print 'Would you like to add another username? (y/n) '
  add_users = gets.chomp.downcase == 'y'
end

puts 'Program Complete.'
