#include "pch.h"
#include <shellapi.h>
#include <Shlwapi.h>
#include "../../lib/Shared/Internal.h"

#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "Shlwapi.lib")

using namespace TwitchInGames;

BrowserAuth::BrowserAuth() : isReady(false) {}

BrowserAuth::~BrowserAuth() {}

std::future<tstring> BrowserAuth::Launch(string_t url, tstring const& state, string_t scheme) {
	UNREFERENCED_PARAMETER(state);
	UNREFERENCED_PARAMETER(scheme);
#ifdef UNIT_TEST
	UNREFERENCED_PARAMETER(url);
	auto fn= [this] {
		return token;
	};
#else
	auto handle= ShellExecute(nullptr, nullptr, url, nullptr, nullptr, SW_SHOWNORMAL);
	auto value= reinterpret_cast<INT_PTR>(handle);
	if(value <= 32) {
		throw TwitchException(FromPlatformError(static_cast<int>(value)));
	}
	auto fn= [this] {
		TokenLock lock(tokenAccessor);
		cv.wait(lock, [this] { return isReady; });
		return token;
	};
#endif
	return std::async(std::launch::deferred, fn);
}

void BrowserAuth::Stop(string_t token_) {
#ifdef UNIT_TEST
	token= token_;
#else
	// Resolve the future returned from Launch.
	TokenLock lock(tokenAccessor);
	token= token_;
	isReady= true;
	cv.notify_all();
#endif
}
