#include "pch.h"
#include "http/HttpRequest.h"
#include "twitchsdk/core/json/reader.h"
#include "Internal.h"

using namespace ttv;
using namespace TwitchInGames;

namespace {
	tstring const helixFollowRootUrl= _T("https://api.twitch.tv/helix/users/follows");
}

std::future<FollowersResponse> FollowersRequest::Fetch(tstring const& clientId, tstring const& token, tstring const& userId) {
	auto fn= [this, clientId, token, userId] {
		tstring url= helixFollowRootUrl + _T("?to_id=") + userId;
		if(Count != 0) {
			url += _T("&first=") + to_tstring(Count);
		}
		if(Direction != PaginationDirection::None && !Cursor.empty()) {
			url += Direction == PaginationDirection::Forward ? _T("&after=") : _T("&before=");
			url += Cursor;
		}
		auto httpResponse= HttpRequest(clientId, token).Get(url);
		ThrowIfResponseFailed(httpResponse);

		// Parse the response as JSON.
		json::Value jsonVal;
		json::Reader jsonReader;
		auto const& response= httpResponse.Response;
		bool parseSucceeded= jsonReader.parse(response.data(), response.data() + response.size(), jsonVal);
		if(!parseSucceeded) {
			DebugWriteLine(_T("[FollowersRequest::Fetch] JSON parsing failed"));
			throw TwitchException(FromPlatformError(ERROR_INVALID_RESPONSE));
		}

		// Send a science event.
		SendTokenScienceEvent(clientId, token, _T("sdk_follow_get_followers"), { { _T("target_user_id"), userId } });

		// Get references for all of the fields.
		FollowersResponse followResponse;
		followResponse.TotalCount= static_cast<unsigned>(jsonVal["total"].asUInt());
		followResponse.Cursor= ToTstring(jsonVal["pagination"]["cursor"].asString());
		auto const& data= jsonVal["data"];
		for(auto const& follower : data) {
			followResponse.Followers.emplace_back(Follower{
				ToTstring(follower["from_id"].asString()),
				ParseTime(follower["followed_at"].asString()),
				});
		}
		return followResponse;
	};
	return std::async(std::launch::deferred, fn);
}
