using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TwitchInGames;
using System;

/// <summary>
/// Updated by ImplicitAuthorizationExample
/// </summary>
public class TwitchSettings {
    internal static string clientId;
    internal static string[] scopes;
    internal static string redirectUri;
    internal static string token;

    public static string ClientId { get { return clientId; } }
    public static string[] Scopes { get { return scopes; } }
    public static string RedirectUri { get { return redirectUri; } }
    public static string Token { get { return token; } }
}


public class ImplicitAuthorizationExample : MonoBehaviour {
    [SerializeField]
    private string clientId;

    [SerializeField]
    private string[] scopes;

    /// <summary>
    /// Default redirect uri for the OAuth implicit flow should not be changed. 
    /// https://dev.twitch.tv/docs/authentication#oauth-implicit-code-flow-user-access-tokens
    /// </summary>
    private string redirectUri = "twig://twig.tv/auth";
    private ClientAuth clientAuth;

    private UserExample userExample;
    private ChatExample chatExample;

    private void Awake() {
        TwitchSettings.clientId = clientId;
        TwitchSettings.scopes = scopes;
        TwitchSettings.redirectUri = redirectUri;

        userExample = GameObject.Find("User").GetComponent<UserExample>();
        chatExample = GameObject.Find("Chat").GetComponent<ChatExample>();
    }

    private void OnDestroy() {
        if (clientAuth != null) {
            clientAuth.Cancel();
#if UNITY_ANDROID
                Destroy(clientAuth);
#else
            clientAuth.Dispose();
#endif
        }
    }

    public void GetToken() {
        StartCoroutine(InternalGetToken());
    }

    /// <summary>
    /// Implementation of OAuth implicit flow. 
    /// https://dev.twitch.tv/docs/authentication#oauth-implicit-code-flow-user-access-tokens
    /// </summary>
    private IEnumerator InternalGetToken() {
        if (clientAuth == null) {
            userExample.Panel.SetActive(false);
            chatExample.SignOut();
            chatExample.Panel.SetActive(false);
            string token = "";
#if UNITY_ANDROID
            clientAuth = gameObject.AddComponent<ClientAuth>();
            var margins = new RectOffset { left = 15, top = Screen.height / 8, right = 15, bottom = Screen.height / 8 };
            yield return clientAuth.StartAuth(clientId, redirectUri, scopes, margins);
            token = clientAuth.AccessToken;
            clientAuth.ClearCookies();
            Destroy(clientAuth);
            clientAuth = null;
#else
            clientAuth = new ClientAuth();
#if UNITY_IOS
            var margins = new RectOffset { left = 15, top = Screen.height / 8, right = 15, bottom = Screen.height / 8 };
            var coroutine = clientAuth.StartAuth(clientId, redirectUri, scopes, margins);
#else
            var coroutine = clientAuth.StartAuth(clientId, redirectUri, scopes);
#endif
            yield return coroutine;
            try {
                token = coroutine.Value;
            }
            catch (Exception ex) {
                Debug.LogException(ex);
            }
            clientAuth.Dispose();
            clientAuth = null;
#endif
            if (String.IsNullOrEmpty(token))
                Debug.LogError("[TwitchInGames] Failed to authorize!");
            else {
                TwitchSettings.token = token;
                Debug.Log("[TwitchInGames] Got Token: " + TwitchSettings.Token + "\nClient ID: " + TwitchSettings.ClientId + "\nScopes: " + string.Join("+",TwitchSettings.Scopes));

                // Display UserInfo
                userExample.Panel.SetActive(true);
                userExample.FetchCurrentUser(clientId, TwitchSettings.Token);
                // Sign in chatroom
                chatExample.Panel.SetActive(true);
                chatExample.SignIn();
            }   
        }
    }
}
