using StartServerWPF.Modules.Main.Models;
using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using WebSocket4Net;

namespace StartServerWPF.Modules.Main
{
    public class WebsocketClient
    {
        public WebSocket webSocket4Net = null;

        public Action<ErrorEventArgs> WebsocketError;
        public Action<string> WebSocketMessageReceived;
        public void WebSocketInit(string url)
        {
            Debug.WriteLine("客户端");
            webSocket4Net = new WebSocket(url);
            webSocket4Net.Opened += WebSocket4Net_Opened;
            webSocket4Net.Error += new EventHandler<ErrorEventArgs>(WebSocket_Error);
            webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
            webSocket4Net.Open();
            Debug.WriteLine("客户端连接成功！");
          
           // thread.Start();
        }
        public void SiginServer(string account,string password)
        {
            isHeartbeat = false;

            string jsonstr= JsonSerializer.Serialize(new CSUserSigin { type = CSMessage.sigin, utype = "device", account=account,password=password});
            SendMes(jsonstr);
            Task.Run(async () =>{
                await Task.Delay(2000);
                isHeartbeat = true;
                SendHeartbeat();
            });
        }

        public void Closed()
        {
            isHeartbeat = false;
        }

        public void SendMes(string message)
        {
            webSocket4Net.Send(message);
        }

        bool isHeartbeat = false;
        private void SendHeartbeat()
        {
            while (isHeartbeat)
            {
                //Console.WriteLine($"客户端发送数据{i++}");
                if (webSocket4Net.State == WebSocketState.Open)
                {
                    webSocket4Net.Send("{\"type\":\"heartbeat\",\"utype\":\"device\"}");
                }
                else if (webSocket4Net.State == WebSocketState.Closed)
                {
                    webSocket4Net.Open();
                    Thread.Sleep(TimeSpan.FromSeconds(10));
                }
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }
        }

        private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            WebSocketMessageReceived?.Invoke(e.Message);
        }

        private void WebSocket4Net_Opened(object sender, EventArgs e)
        {
          
        }
        void WebSocket_Error(object sender, ErrorEventArgs e)
        {
            WebsocketError?.Invoke(e);
            Debug.WriteLine("websocket_Error:" + e.Exception.ToString());
        }
    }
}
