require 'uri'
require 'net/http'
require 'json'
require 'cgi'

uri = URI('https://opentdb.com/api.php?amount=1')
res = Net::HTTP.get_response(uri)

trev_running = false

if res.is_a?(Net::HTTPSuccess)
  question = JSON.parse(res.body)
  puts question.inspect

  difficulty = question["results"][0]["difficulty"]

  puts difficulty

  question_text = CGI.unescapeHTML(question["results"][0]["question"])
  answer = question["results"][0]["correct_answer"]

  puts answer

  category = question["results"][0]["category"]

  answers = question["results"][0]["incorrect_answers"]
  answers.push(answer)

  answers.shuffle!
#  puts answers.inspect

  puts "[" + category + "] " + question_text

  out_str = ""

  current_answer = "A"

  real_answer = ""

  max_answer = answers.max{|c1, c2| c1.length <=> c2.length}
  max_length = max_answer.length + 2 # 2 for padding a bit...

  puts "max_length.to_s = " + max_length.to_s

  padded_answers = answers.map{|v| v.ljust(max_length.to_i) }

  answers_shown = 0

  padded_answers.each{ |a|
    answers_shown = answers_shown + 1

    if a == answer then
      real_answer = current_answer.clone
    end

    out_str = out_str + current_answer + ") " + CGI.unescapeHTML(a) + " "

    if answers_shown % 2 == 0 then
      out_str.strip!
      out_str = out_str + "\n"
    end

    current_answer.next!
  }

  puts real_answer
  out_str.delete_suffix!(" |")
  puts out_str.strip

  puts "TRIVIA STARTING IN 5 SECONDS!"
  puts Time.now.to_i.to_s + " start 5s timer..."
  sleep(5)
  trev_running = true

#  puts Time.now.to_i.to_s + " OK ABOUT TO START??"
  puts "You have 30 seconds!  Go!"

#  puts real_answer

  puts Time.now.to_i.to_s + " start guess time"

  sleep(30)

  puts Time.now.to_i.to_s + " end time"

# Check the user answers
# Check their times, calc score and save it, 
# Reset answer array, save.

  trev_running = false
end

# have trigger for !trev to start.  Flag something to flip playing to true.  
# have trigger for guesses- matches on case insensitive ^ABCDTF$
