//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//

#include "pch.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include "MainPage.xaml.h"

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace TwitchInGames;
using namespace UwpApp1;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

MainPage::MainPage() {
	InitializeComponent();
}

#include "../Win32App1/FlowOne.inl"

static std::unique_ptr<ClientAuth> clientAuth;

void UwpApp1::MainPage::FlowOneButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) {
	auto token= DoFlow1();
	auto content= ref new Platform::String(token.c_str());
	auto messageBox= ref new Windows::UI::Popups::MessageDialog(content, "Flow One");
	messageBox->ShowAsync();
}


void UwpApp1::MainPage::FlowTwoButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) {
	clientAuth= std::make_unique<ClientAuth>();
	static string_t const clientId= L"dviaxdls39mj44cdnei76mj2dlig33";
	auto result= clientAuth->StartAuth(clientId, L"twig://twig.tv/auth", { L"user:read:email" });
	auto const fn= [](auto result) {
		auto token= result.get();
		OutputDebugString(token.c_str());
		OutputDebugString(L"\n");
		auto user= User::FetchCurrent(clientId, token.c_str()).get();
		auto emailAddress= user.Email;
		OutputDebugString(emailAddress.c_str());
		OutputDebugString(L"\n");
	};
	static std::future<void> task= std::async(std::launch::async, fn, std::move(result));
}

void MainPage::OnActivated(Platform::String^ activationUri) {
	clientAuth->Finish(activationUri->Data());
}


void UwpApp1::MainPage::CancelFlowTwoButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) {
	clientAuth->Cancel();
}
