defmodule SomethingErlang.AwfulApi.Client do
  @base_url "https://forums.somethingawful.com/"
  @user_agent "SomethingErlangClient/0.1"

  def thread_doc(id, page, user) do
    resp = new_request(user) |> get_thread(id, page)
    :unicode.characters_to_binary(resp.body, :latin1)
  end

  def thread_lastseen_page(id, user) do
    resp = new_request(user) |> get_thread_newpost(id)
    %{status: 302, headers: headers} = resp
    {"location", redir_url} = List.keyfind(headers, "location", 0)
    [_, page] = Regex.run(~r/pagenumber=(\d+)/, redir_url)
    page |> String.to_integer()
  end

  def bookmarks_doc(page, user) do
    resp = new_request(user) |> get_bookmarks(page)
    :unicode.characters_to_binary(resp.body, :latin1)
  end

  defp get_thread(req, id, page \\ 1) do
    url = "showthread.php"
    params = [threadid: id, pagenumber: page]
    Req.get!(req, url: url, params: params)
  end

  defp get_thread_newpost(req, id) do
    url = "showthread.php"
    params = [threadid: id, goto: "newpost"]
    Req.get!(req, url: url, params: params, follow_redirects: false)
  end

  defp get_bookmarks(req, page \\ 1) do
    url = "bookmarkthreads.php"
    params = [pagenumber: page]
    Req.get!(req, url: url, params: params)
  end

  defp new_request(user) do
    Req.new(
      base_url: @base_url,
      user_agent: @user_agent,
      cache: true,
      headers: [cookie: [cookies(%{bbuserid: user.id, bbpassword: user.hash})]]
    )

    #    |> Req.Request.append_request_steps(inspect: &IO.inspect/1)
  end

  defp cookies(args) when is_map(args) do
    Enum.map_join(args, "; ", fn {k, v} -> "#{k}=#{v}" end)
  end
end