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

using WebSocketSharp;

using ETSI.ARF.WorldAnalysis;
using ETSI.ARF.WorldAnalysis.REST;
using ETSI.ARF.OpenAPI.WorldAnalysis;
using Pose = ETSI.ARF.OpenAPI.WorldAnalysis.Pose;
using UnityEngine.InputSystem;

public class TestWebSocketsClient : MonoBehaviour
{
    public WorldAnalysisREST rest;
    public GameObject asset1;

    private WebSocketSharp.WebSocket webSocket;
    string websocketServer;
    bool websocketConnected = false;

    // Start is called before the first frame update
    void Start()
    {
        if (asset1 != null) asset1.GetComponent<Renderer>().material.color = Color.red;

        rest.CheckServer();
        rest.PrintCapabilities();

        //websocketServer = rest.GetWebSocketEndpoint();
        websocketServer = "ws://localhost:61788/ws";

        WebSocketConnect();
    }

    // Update is called once per frame
    bool updateAsset1 = false;
    Color asset1Color = Color.grey;
    void Update()
    {
        if (Keyboard.current.spaceKey.wasPressedThisFrame)
        {
            webSocket.Send("StartSendingPose:10");
        }

        if (updateAsset1)
        {
            updateAsset1 = false;
            asset1.GetComponent<Renderer>().material.color = asset1Color;
        }
    }

    void SetColor(Color c)
    {
        updateAsset1 = true;
        asset1Color = c;
    }

    private void OnDestroy()
    {
        if (websocketConnected) WebSocketClose();
    }

    //
    // WebSocket methods
    //
    public void WebSocketClose()
    {
        webSocket.Send("unregister");
        webSocket.Close();
    }

    public void WebSocketConnect()
    {
        webSocket = new WebSocketSharp.WebSocket(websocketServer.ToString());

        webSocket.OnOpen += (sender, e) =>
        {
            websocketConnected = true;
            Debug.Log("[WS] Connected");
            webSocket.Send("client:UnitySceneManagement");
        };
        webSocket.OnClose += (sender, e) =>
        {
            websocketConnected = false;
            SetColor(Color.red);
            Debug.Log("[WS] Disconnected");
        };
        webSocket.OnError += (sender, e) => Debug.Log("[WS] Error!");
        webSocket.OnMessage += (sender, e) => WebSocketHandleMessage(e.Data);
        webSocket.Connect();
    }

    bool ok = false;
    public void WebSocketHandleMessage(string data)
    {
        Debug.Log("[WS] Receiving: " + data);

        if (data.Contains("You are now registered"))
        {
            ok = true;
            SetColor(Color.yellow);
            webSocket.Send("StartSendingPose:10");
        }
        else if (data == "Stop")
        {
            SetColor(Color.yellow);
            //ok = false;
        }
        else if (ok)
        {
            if (data.Contains("estimationState"))
            {
                // Handle pose
                Pose p = JsonUtility.FromJson<Pose>(data);
                Debug.Log("[WS][Pose] State: " + p.EstimationState.ToString());
                if (p.EstimationState == PoseEstimationState.OK)
                {
                    if (asset1 != null)
                    {
                        SetColor(Color.green);
                        //asset1.transform.rotation = WorldAnalysisUnityHelper.ConvertETSIARFQuaternionToUnity(p.Value.ro)
                    }
                }
                else
                {
                    SetColor(Color.yellow);
                }
            }
        }
    }
}
