using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

namespace TwitchInGames {
    public class ServerAuth {
        public string AccessToken { get; private set; } = "";
        public string RefreshToken { get; private set; } = "";

        public string StartAuth(string clientId, string redirectUri, IEnumerable<string> scopes) {
            // Compose the authentication URL with thirty-two characters of
            // random state.
            Cancel();
            var escapedResponseType = WWW.EscapeURL("code");
            var escapedClientId = WWW.EscapeURL(clientId);
            var escapedRedirectUri = WWW.EscapeURL(redirectUri);
            var scope = scopes != null ? String.Join(" ", scopes.ToArray()) : "";
            var escapedScope = WWW.EscapeURL(scope);
            var r = new RNGCryptoServiceProvider();
            var bytes = new byte[32];
            r.GetBytes(bytes);
            var state = WWW.EscapeURL(new String(bytes.Select(i => (char)(((i & 0x6f) | 0x40) + 1)).ToArray()));
            var url = $"https://id.twitch.tv/oauth2/authorize?response_type={escapedResponseType}&client_id={escapedClientId}&redirect_uri={escapedRedirectUri}&scope={escapedScope}&state={state}";

            // Open the platform's browser.
            Application.OpenURL(url);
            return state;
        }

        public void Finish(string accessToken, string refreshToken) {
            AccessToken = accessToken ?? "";
            RefreshToken = refreshToken ?? "";
        }

        public void Cancel() {
            Finish("", "");
        }
    }
}
