using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using WebSocketSharp;
using WebSocketSharp.Server;

public class StreamDeckHandler : WebSocketBehavior
{
    public DebugTextController DebugController { get; set; }

    protected override void OnOpen()
    {
        if (DebugController == null)
        {
            Debug.LogError("DebugTextController가 초기화되지 않았습니다!");
            return;
        }

        var data = new TextListData
        {
            type = "textList",
            texts = DebugController.debugTextinfo.Select(x => x.text).ToList()
        };
        Send(JsonUtility.ToJson(data));
    }

    protected override void OnMessage(MessageEventArgs e)
    {
        try
        {
            var data = JsonUtility.FromJson<CommandData>(e.Data);
            if (int.TryParse(data.command, out int index))
            {
                DebugController?.Set(index);
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"커맨드 처리 중 오류: {ex.Message}");
        }
    }
}

[System.Serializable]
public class TextListData
{
    public string type;
    public List<string> texts;
}

[System.Serializable]
public class CommandData
{
    public string command;
}

public class StreamDeckConnection : MonoBehaviour
{
    [SerializeField] private DebugTextController debugTextController;
    private WebSocketServer wssv;
    private readonly int port = 8087;

    void Awake()
    {
        if (debugTextController == null)
        {
            debugTextController = GetComponent<DebugTextController>();
            
            if (debugTextController == null)
            {
                debugTextController = GetComponentInChildren<DebugTextController>();
                if (debugTextController == null)
                {
                    debugTextController = GetComponentInParent<DebugTextController>();
                }
            }
        }
    }

    void Start()
    {
        if (debugTextController == null)
        {
            Debug.LogError("DebugTextController가 할당되지 않았습니다!");
            return;
        }

        wssv = new WebSocketServer(port);
        wssv.AddWebSocketService<StreamDeckHandler>("/", handler => handler.DebugController = debugTextController);
        wssv.Start();
    }

    void OnDestroy()
    {
        if (wssv != null)
        {
            wssv.Stop();
        }
    }
}