require 'post_request'
require 'json'

class Imgur
  attr_accessor :error_message
  
  # Methods to refresh_token and create_album go here
  def renew_auth_token(client_id, client_secret, refresh_token)
    
    form_data = {
    	"client_id" => client_id,
    	"client_secret" => client_secret,
    	"refresh_token" => refresh_token,
    	"grant_type" => "refresh_token"
    }
    
    post_request = PostRequest.new("https://api.imgur.com/oauth2/token", form_data)

    begin
      response = post_request.post
      json = JSON.parse(response)
    rescue
      @error_message = $!
      return false
    end

    if json["access_token"] and json["refresh_token"]
      $dz.save_value("access_token", json["access_token"])
      $dz.save_value("refresh_token", json["refresh_token"])
      return json["access_token"]
    else
      @error_message = "Invalid JSON received: #{json.inspect}"
      return false
    end
  end
end