using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using TwitchLib.Client.Models;
using TwitchLib.Unity;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Login : MonoBehaviour {
    /// <summary>
    /// Not so secret huehue
    /// </summary>
    public const string SECRET_FILENAME = "secret.txt";
    public static string Username;
    public static string Token;
    public Button LoginButton;
    public Toggle RememberMeToggle;
    public InputField UsernameField;
    public InputField TokenField;
    // Start is called before the first frame update
    void Start() {
        if (File.Exists(SECRET_FILENAME)) {
            using StreamReader reader = new StreamReader(SECRET_FILENAME); // looks for local folder
            Username = reader.ReadLine().Trim(); // line 1 is channel name
            Token = reader.ReadLine().Trim(); // line 2 is access token
            if(string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Token)) {
                // invalid credentials
                return;
            }
            //Debug.Log($"{Username} {Token}");
            CheckCredentials();
        }
        LoginButton.interactable = false;
        UsernameField.onEndEdit.AddListener((s) => {
            Username = s.Trim();
            if (!string.IsNullOrEmpty(Token)) {
                LoginButton.interactable = AwaitLoginAttempt().Result;
            }
        });
        TokenField.onEndEdit.AddListener((s) => {
            Token = s.Trim();
            LoginButton.interactable = AwaitLoginAttempt().Result;
        });
    }

    private void CheckCredentials() {
        if (!AwaitLoginAttempt().Result) {
            Debug.LogError("Invalid Credentials");
            return;
        }
        SceneManager.LoadScene("main");
    }

    private Task<bool> AwaitLoginAttempt() {
        TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
        try {
            Debug.Log("Checking Username...");
            ConnectionCredentials cc = new ConnectionCredentials(Username, Token);
            // this shit not working yet
            //var client = new Client();
            //client.OnIncorrectLogin += (sender, e) => {
            //    Debug.LogError("Invalid Login.");
            //    tcs.TrySetResult(false);
            //};
            //client.OnConnected += (sender, e) => {
            //    client.Disconnect();
            //    tcs.TrySetResult(true);
            //    Debug.LogError("Connection Successful.");
            //};
            //client.Initialize(cc, Username);
            //client.Connect();
            tcs.SetResult(true);
        } catch (Exception e){
            Debug.LogError(e.Message);
            tcs.SetResult(false);
        }
        Debug.Log("Username Checked.");
        return tcs.Task;
    }

    // Update is called once per frame
    void Update() {

    }

    public void OpenTokenGeneratorWebsite() {
        Application.OpenURL("https://twitchtokengenerator.com/");
    }

    public void SaveCredentials() {
        Username = UsernameField.text.Trim();
        Token = TokenField.text.Trim();
        if (RememberMeToggle) {
            if (File.Exists(SECRET_FILENAME)) {
                File.Delete(SECRET_FILENAME);
            }
            using StreamWriter streamWriter = new StreamWriter(SECRET_FILENAME);
            streamWriter.WriteLine(Username);
            streamWriter.WriteLine(Token);
        }
        CheckCredentials();
    }
}
