using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;

namespace TwitchInGames.Test {
    public class Test_AndroidPlugin : MonoBehaviour {

        class AndroidPluginCallback : AndroidJavaProxy {
            public AndroidPluginCallback() : base("tv.twitch.twiglib.ReceiveCallBack") { }
            public virtual void invoke(string userName, string message) {
                Debug.Log("RecevieCallBack.invoke " + userName + ": " + message);
            }
        }

            [SerializeField]
        private Transform outPutPanelTrans;

        [SerializeField]
        private GameObject messagePrefab;

        [SerializeField]
        private Text countText;

        [SerializeField]
        private Text text;

        private Queue<GameObject> messages = new Queue<GameObject>(32);

        private AndroidJavaObject twigtest;
        private AndroidJavaObject chat;
        private AndroidJavaObject channel;

        // Use this for initialization
        void Start() {

            var twiglog = new AndroidJavaClass("tv.twitch.twiglib.Logger");
            twiglog.CallStatic("SetReceiver", this.gameObject.name, "Logger");
            twiglog.CallStatic("d", "Unity", "Link successful!");

            twigtest = new AndroidJavaObject("tv.twitch.twiglib.TwigTest");
            text.text = "Java: " + twigtest.CallStatic<string>("GetLibName");

            twigtest.Call("Initialize");
            //twigtest.Call("SendHttpRequest");
            text.text = text.text + " " + twigtest.Call<string>("GetVersion");

            StartCoroutine(Run());

            //Debug.Log("Start!!");

            //chat = new AndroidJavaObject("tv.twitch.twiglib.Chat");
            //chat.Call("SignIn", "dviaxdls39mj44cdnei76mj2dlig33", "0h5oyj6s9v39gazh7o6wnwxhjsvdy6");

            //StartCoroutine(RunChat());
        }

        private IEnumerator RunChat() {
            var callback = new AndroidPluginCallback();
            yield return new WaitUntil(() => chat.Call<bool>("hasSignIn"));
            Logger("Unity Signed in!");
            chat.Call("Join", "twigsdk", callback);
            yield return new WaitForSeconds(2);
            chat.Call("SendLine", "twigsdk", "Message from Android");
            yield return new WaitForSeconds(5);
            chat.Call("Depart", "twigsdk");
            yield return new WaitForSeconds(2);
            chat.Call("SignOut");
            yield return new WaitUntil(() => !chat.Call<bool>("hasSignIn"));
            Logger("Unity Signed out!");
        }


        private IEnumerator Run() {
            yield return new WaitForSeconds(1);
            twigtest.Call("SetLocalLanguage");
            twigtest.Call("Login");
            yield return new WaitUntil(() => twigtest.Call<bool>("hasLogin"));
            Logger("Unity Login successful!");
            //twigtest.Call("ChatConnect");
            //yield return new WaitUntil(() => twigtest.Call<bool>("ChatHasConnected"));
            //twigtest.Call("ChatSendMessage");
            //yield return new WaitForSeconds(5);
            //twigtest.Call("ChatDisconnect");
            //yield return new WaitUntil(() => !twigtest.Call<bool>("ChatHasConnected"));
            //twigtest.Call("Logout");
            //yield return new WaitUntil(() => !twigtest.Call<bool>("hasLogin"));
            //Logger("Unity Logout successful!");
        }

        public void GetJavaMessage(string str) {
            this.OutputNewLine("Java", str);
        }

        internal void Logger(string message) {
            string[] strs = message.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
            OutputNewLine(strs[0], strs[1]);
        }

        private void OutputNewLine(string name, string value) {
            GameObject gameobject;
            if (messages.Count >= 32) {
                gameobject = messages.Dequeue();
            }
            else {
                gameobject = Instantiate(messagePrefab, outPutPanelTrans);
            }
            Dictionary<string, string> dict = new Dictionary<string, string>(1);
            dict.Add(name, value);
            gameobject.GetComponent<InfoHolder>().Init(dict);
            gameobject.transform.SetAsFirstSibling();
            messages.Enqueue(gameobject);
        }
    }
}

