     hackney = [basic_auth: {Application.fetch_env!(:vutuv, Vutuv.Endpoint)[:browserstack_user], Application.fetch_env!(:vutuv, Vutuv.Endpoint)[:browserstack_password]}]
 
     case HTTPoison.get("https://www.browserstack.com/screenshots/#{job_id}.json", %{},[ hackney: hackney ]) do
-      {:ok, %HTTPoison.Response{status_code: 404}} -> nil
-      {:ok, %HTTPoison.Response{body: body, headers: headers}} ->
+      {:ok, %HTTPoison.Response{body: body, headers: headers, status_code: 200}} ->
          decoded_body = body |> Poison.decode!
          {:ok, results} = Map.fetch(decoded_body, "screenshots")
          {:ok, image_url} = Map.fetch(List.first(results), "image_url")

    image_url(job_id, 0)
  end

  # When the counter reaches 7 stop
  defp image_url(job_id, 7) do
    fetch_image_url(job_id)
  end

  # Try every 25 seconds to fetch the image_url
  defp image_url(job_id, count) do
    case fetch_image_url(job_id) do
      nil ->
        :timer.sleep(25000)
        image_url(job_id, count + 1)
      url -> url
    end

  def generate_screenshot(url) do
    job_id = new_job_id(url)

    if job_id do
      image_url(job_id)
      |> HTTPoison.get([], [timeout: 1500, recv_timeout: 1500])
      |> case do
        {:ok, %HTTPoison.Response{status_code: 404}} -> nil
        {:ok, %HTTPoison.Response{body: body, headers: headers}} ->
          {_, content_type} = List.keyfind(headers, "Content-Type", 0)
          file_extension = String.split(content_type, "/")
                           |> List.last
          filename = "#{url.id}.#{file_extension}"
          temp_dir_path = System.tmp_dir
          temp_file = "#{temp_dir_path}/screen-shot-#{filename}"
                      |> String.replace("//","/")
          File.rm(temp_file)
          File.write(temp_file, body)
          upload = %Plug.Upload{content_type: content_type,
                   filename: filename,
                   path: temp_file}
          url
          |> Url.changeset(%{screenshot: upload})
          |> Repo.update
          File.rm(temp_file)
        _ -> nil
      end
    end
  end

