using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;

namespace TwitchInGames.Test {
    public class Test_ChatUnit : MonoBehaviour {
#pragma warning disable 649 // Field '*' is never assigned to, and will always have its default value *
        [SerializeField]
        private Chat _chat;

        [SerializeField]
        private string _token;

        [SerializeField]
        private List<string> _channelNames;
#pragma warning restore 649

        private static string _clientId = "dviaxdls39mj44cdnei76mj2dlig33";

        void Start() {
            _chat = gameObject.AddComponent<Chat>();
            StartCoroutine(SignIn());
        }

        private IEnumerator SignIn() {
            var coroutine = _chat.SignIn(_clientId, _token);
            yield return coroutine;

            try {
                var result = coroutine.Value;
            } catch(Exception ex) {
                Debug.LogErrorFormat("Test_ChatUnit.SignIn error: {0}", ex);
                yield break;
            }
            yield return OnSignInSuccess(_chat);
        }

        private void Update() {
            if(Input.GetKeyDown(KeyCode.Alpha1)) {
                _chat.Channels["twiggieg"].Depart();
                StringBuilder sb = new StringBuilder();
                foreach(var channel in _chat.Channels.Values) {
                    sb.Append(channel.Name);
                    sb.Append(' ');
                }
                Debug.Log(sb.ToString());

                _chat.Channels["twiggieg"].SendLine("I'm not dying yet!!!"); // Should throw exception
            }
        }

        private IEnumerator OnSignInSuccess(Chat chat) {
            foreach(string channelName in _channelNames) {
                var coroutine = chat.JoinChannel(channelName, null);
                yield return coroutine;
                try {
                    var channel = coroutine.Value;
                    OnJoinSuccess(channel);
                } catch(Exception ex) {
                    Debug.LogErrorFormat("Test_ChatUnit.OnSignInSuccess error: {0}", ex);
                    yield break;
                }
            }
        }

        private void OnJoinSuccess(Chat.Channel channel) {
            if(channel.Name == "twiggieg") {
                channel.SendLine(String.Format(("{0}: {1}"), gameObject.name, Time.time.ToString()));
                channel.SendLine(String.Format(("{0}: {1}"), gameObject.name, Time.time.ToString()));
                channel.SendLine(String.Format(("{0}: {1}"), gameObject.name, Time.time.ToString()));
                channel.SendLine(String.Format(("{0}: {1}"), gameObject.name, Time.time.ToString()));
                channel.SendLine(String.Format(("{0}: {1}"), gameObject.name, Time.time.ToString()));
            }
        }
    }
}
