/*
Copyright 2019 Dr. Thomas Benjamin Senior, Michael Zoeller 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;
using WebuSocketCore;
using Newtonsoft.Json.Linq;

namespace EyeSkills
{
    public class NetworkManager : MonoBehaviour
    {
        public string server = "";
        public string uuid = "";
        public string practitioner = "practitioner1";

        WebuSocket webSocket;

        static readonly Queue<Action> _executionQueue = new Queue<Action>();

        public Dictionary<string, float> floatQueue = new Dictionary<string, float>();
        public Dictionary<string, bool> buttonQueue = new Dictionary<string, bool>();

        // singleton like access pattern
        public static NetworkManager instance;

        void Awake()
        {
            if (instance == null)
                instance = this;
            else if (instance != this)
                Destroy(gameObject);

            DontDestroyOnLoad(gameObject);

            WebSocketInit();
        }

        public void Update()
        {
            lock (_executionQueue)
            {
                while (_executionQueue.Count > 0)
                {
                    _executionQueue.Dequeue().Invoke();
                }
            }
        }

        public void Enqueue(IEnumerator action)
        {
            lock (_executionQueue)
            {
                _executionQueue.Enqueue(() => { StartCoroutine(action); });
            }
        }

        public void Enqueue(Action action)
        {
            Enqueue(ActionWrapper(action));
        }

        IEnumerator ActionWrapper(Action a)
        {
            a();
            yield return null;
        }

        void OnApplicationQuit()
        {
            if (webSocket != null)
                webSocket.Disconnect();
        }

        void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            if (webSocket == null)
                return;

            cam = null;

            JObject j = new JObject();
            j.Add("scene_name", scene.name);
            Send("remote_scene_loaded", j.ToString());
        }

        void OnSceneUnloaded(Scene scene)
        {
            if (webSocket == null)
                return;
        }

        void OnEnable()
        {
            Application.logMessageReceived += HandleLog;
            SceneManager.sceneLoaded += OnSceneLoaded;
            SceneManager.sceneUnloaded += OnSceneUnloaded;
        }

        void OnDisable()
        {
            Application.logMessageReceived -= HandleLog;
            SceneManager.sceneLoaded -= OnSceneLoaded;
            SceneManager.sceneUnloaded -= OnSceneUnloaded;
        }

        void HandleLog(string logString, string stackTrace, LogType type)
        {
            if (webSocket == null)
                return;

            JObject j = new JObject();
            j.Add("timestamp", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
            j.Add("logtype", type.ToString());
            j.Add("logstring", logString);
            j.Add("stacktrace", stackTrace);

            Send("log", j.ToString());
        }

        public string GetUUID()
        {
            uuid = PlayerPrefs.GetString("EyeSkills.UUID", "");
            if (uuid == "")
            {
                uuid = System.Guid.NewGuid().ToString();
                PlayerPrefs.SetString("EyeSkills.UUID", uuid);
            }

            return uuid;
        }

        string GetPractitioner()
        {
            practitioner = PlayerPrefs.GetString("EyeSkills.Practitioner", "");
            return practitioner;
        }

        void WebSocketInit()
        {
            uuid = GetUUID();
            practitioner = GetPractitioner();
            string username = PlayerPrefs.GetString("EyeSkills.Name", "");

            if (server == "")
            {
                Debug.LogWarning("Network: WebSocket server url empty. Connection abort.");
                return;
            }

            if (practitioner == "")
            {
                Debug.LogWarning("Network: No practitioner configured. Connection abort.");
                return;
            }

            webSocket = new WebuSocket(
                server,
                1024,
                // handler for connection established to server.
                () =>
                {
                    Debug.Log("Network: Connected to websocket server. Sending auth...");
                    Send("register", "{\"client_type\":\"slave\",\"name\":\"" + username + "\"}");
                },
                // handler for receiving data from server.
                datas =>
                {
                    while (0 < datas.Count)
                    {
                        ArraySegment<byte> data = datas.Dequeue();

                        byte[] bytes = new byte[data.Count];
                        Buffer.BlockCopy(data.Array, data.Offset, bytes, 0, data.Count);

                        Debug.Log("message:" + Encoding.UTF8.GetString(bytes));
                        HandleMessage(Encoding.UTF8.GetString(bytes));
                    }
                },
                () => { Debug.Log("Network: Received server ping. Automatically ponged."); },
                closeReason =>
                {
                    Debug.Log("Network: Connection closed, closeReason:" + closeReason);
                    Enqueue(_reconnect());
                },
                (errorEnum, exception) =>
                {
                    // Debug.LogError ("error, errorEnum:" + errorEnum + " exception:" + exception);
                },
                new Dictionary<string, string>
                {
                    // optional WebSocket connection header parameters
                }
            );
        }

        IEnumerator _reconnect()
        {
            if (server == "")
                yield break;

            if (webSocket == null)
            {
                WebSocketInit();
                yield break;
            }

            while (!webSocket.IsConnected())
            {
                Debug.Log("Network: Attempting to reconnect...");
                webSocket?.Disconnect();
                yield return new WaitForSeconds(1f);
                WebSocketInit();
                yield return new WaitForSeconds(5f);
            }
        }

        public void Reconnect()
        {
            StartCoroutine(_reconnect());
        }

        int width = -1, height = -1;

        Texture2D tex;
        RenderTexture rTex = null;

        Camera cameraLeft, cameraRight;
        Camera cam;

        string eye;
        bool stereo;

        IEnumerator RecordFrame()
        {
            yield return new WaitForEndOfFrame();

            if (!cam)
            {
                stereo = GameObject.Find("Main Camera Left");

                if (stereo)
                {
                    cameraLeft = GameObject.Find("Main Camera Left").GetComponent<Camera>();
                    cameraRight = GameObject.Find("Main Camera Right").GetComponent<Camera>();
                    cam = cameraLeft;
                }
                else
                    cam = Camera.main;
            }

            if (width != cam.pixelWidth || height != cam.pixelHeight)
            {
                Debug.Log("Network: Camera resolution changed. Recreating render textures. Resolution: " + width + "*" +
                          height);
                width = cam.pixelWidth;
                height = cam.pixelHeight;
                if (tex != null)
                {
                    Destroy(tex);
                    Destroy(rTex);
                }

                tex = new Texture2D(width, height, TextureFormat.RGB24, false);
#if !UNITY_EDITOR
				rTex = new RenderTexture (width, height, 0, RenderTextureFormat.RGB565);
#endif
            }

            if (stereo)
            {
                cam.targetTexture = rTex;
#if !UNITY_EDITOR
                RenderTexture.active = rTex;
#endif
                cam.Render();
            }

            tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            tex.Apply();

#if !UNITY_EDITOR
			RenderTexture.active = null;
#endif
            cam.targetTexture = null;

#if !UNITY_EDITOR
            // give the pipeline a chance to complete all of the commands normally without having to stall to fulfill getdata request
            // see https://answers.unity.com/questions/465409/reading-from-a-rendertexture-is-slow-how-to-improv.html
            yield return 0;
#endif

            byte[] jpeg = tex.EncodeToJPG(10);

            eye = "";
            // alternate vr cameras each frame
            if (cam == cameraLeft)
            {
                eye = "left";
                cam = cameraRight;
            }
            else if (cam == cameraRight)
            {
                eye = "right";
                cam = cameraLeft;
            }

            Send("screenshot", "{\"jpeg\":\"" + Convert.ToBase64String(jpeg) + "\",\"eye\":\"" + eye + "\"}");
        }

        IEnumerator LoadMenu()
        {
            yield return 0;
            SceneManager.LoadScene("Menu");
        }

        IEnumerator ConfigReply(string id, string s)
        {
            ConfigManager.instance.ConfigReply(id, s);
            yield return 0;
        }

        void HandleMessage(string data)
        {
            var d = JObject.Parse(data);

            switch (JObject.Parse(data)["type"].Value<string>())
            {
                case "stream":
                    Enqueue(RecordFrame());
                    break;
                case "load_menu":
                    Enqueue(LoadMenu());
                    break;
                case "config_reply":
                    Enqueue(ConfigReply(d["data"]["id"].Value<string>(), d["data"]["config"].Value<string>()));
                    break;
                case "set_config":
                    Enqueue(ConfigReply(d["data"]["id"].Value<string>(), d["data"]["config"].ToString()));
                    break;
                case "remote_server_set":
                    string type = d["data"]["type"].Value<string>();
                    string id = d["data"]["id"].Value<string>();
                    if (type == "float")
                        floatQueue[id] = d["data"]["value"].Value<float>();
                    if (type == "button")
                        buttonQueue[id] = true;
                    break;
            }
        }

        public void Send(string type, string msg = "\"\"")
        {
            if (webSocket == null)
                return;

            webSocket.SendString(
                "{\"type\":\"" + type + "\", \"uuid\":\"" + uuid + "\", \"practitioner\":\"" + practitioner +
                "\",\"data\":" + msg + "}"
            );
        }

        public void RegisterScene(string name, string description)
        {
            StartCoroutine(_registerScene(name, description));
        }

        IEnumerator _registerScene(string name, string description)
        {
            JObject j = new JObject();
            j.Add("remote_type", "scene");
            j.Add("name", name);
            j.Add("description", description);
            yield return 0;
            Send("remote_register", j.ToString());
        }

        public void RegisterFloat(string id, float min, float max, float step, string name, string description)
        {
            JObject j = new JObject();
            j.Add("remote_type", "float");
            j.Add("id", id);
            j.Add("min", min);
            j.Add("max", max);
            j.Add("step", step);
            j.Add("name", name);
            j.Add("description", description);
            Send("remote_register", j.ToString());
        }

        public bool FloatChanged(string id)
        {
            return floatQueue.ContainsKey(id);
        }

        public float GetFloat(string id)
        {
            if (!floatQueue.ContainsKey(id))
                return 0;

            float value = floatQueue[id];
            floatQueue.Remove(id);

            return value;
        }

        public void SetFloat(string id, float value)
        {
            JObject j = new JObject();
            j.Add("remote_type", "float");
            j.Add("id", id);
            j.Add("value", value);
            Send("remote_client_set", j.ToString());
        }

        public void RegisterButton(string id, string name, string description)
        {
            JObject j = new JObject();
            j.Add("remote_type", "button");
            j.Add("id", id);
            j.Add("name", name);
            j.Add("description", description);
            Send("remote_register", j.ToString());
        }

        public bool GetButton(string id)
        {
            if (!buttonQueue.ContainsKey(id))
                return false;

            buttonQueue.Remove(id);
            return true;
        }

        public void Report(string id, object data)
        {
            JObject j = new JObject();
            j.Add("id", id);
            j.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
            j.Add("data", JsonConvert.SerializeObject(data));
            Send("report", j.ToString());
        }
    }
}
