using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Waste.Application;

namespace Waste.Web.Entry.Pages.Socket
{
    public class TestModel : PageModel
    {
        private readonly ILoggerService _loggerService;
        public TestModel(ILoggerService loggerService)
        {
            _loggerService = loggerService;
        }
        public async Task OnGetAsync()
        {
          await  OnGetTestAsync();
        }

        public async Task OnGetTestAsync()
        {
            string BaseUrl = "wss://api.device.suzhou.ljflytjl.cn/device_rpc";
            ClientWebSocket client = new ClientWebSocket();
            client.Options.AddSubProtocol("protocol1");
            client.Options.SetRequestHeader("device", "08d9588d-4796-48f9-8c5b-f28f271b51d0");
            client.Options.SetRequestHeader("secret", "bfbaf98fb5b343b2");
            client.Options.SetRequestHeader("time", GetTimestamp().ToString());
            client.Options.SetRequestHeader("os", "12");
            client.Options.SetRequestHeader("script", "2");
            client.Options.SetRequestHeader("baseProgrameLang", "10");
            client.Options.SetRequestHeader("dev", "true");
            await client.ConnectAsync(new Uri(BaseUrl), CancellationToken.None);
            Console.WriteLine("Connect success");

            await client.SendAsync(new ArraySegment<byte>(AddSeparator(Encoding.UTF8.GetBytes(@"{""protocol"":""json"", ""version"":1}")))
      , WebSocketMessageType.Text, true, CancellationToken.None);//发送握手包
            Console.WriteLine("Send success");
          
            var buffer = new ArraySegment<byte>(new byte[1024]);
            while (client.State == WebSocketState.Open)
            {
                var bytes = Encoding.UTF8.GetBytes(@"{
    ""type"": 6
    }");//发送远程调用 log方法
                await client.SendAsync(new ArraySegment<byte>(AddSeparator(bytes)), WebSocketMessageType.Text, true, CancellationToken.None);


                await client.ReceiveAsync(buffer, CancellationToken.None);
                byte[] databytes = new byte[buffer.Count];
                for(int i = buffer.Offset; i < (buffer.Offset + buffer.Count); i++)
                {
                    var aa = buffer.Array[i];
                    databytes[i] = aa;
                }
                var str = Encoding.UTF8.GetString(databytes);
                //保存数据
                _loggerService.AddLogger(str, 1);
                Console.WriteLine(str);
            }
        }

        private static byte[] AddSeparator(byte[] data)
        {
            List<byte> t = new List<byte>(data) { 0x1e };//0x1e record separator
            return t.ToArray();
        }
        private static byte[] RemoveSeparator(byte[] data)
        {
            List<byte> t = new List<byte>(data);
            t.Remove(0x1e);
            return t.ToArray();
        }
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        private int GetTimestamp()
        {
            DateTime dateTimeStart = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1, 8, 0, 0));
            int timestamp = Convert.ToInt32((DateTime.Now - dateTimeStart).TotalSeconds);
            return timestamp;
        }
        /// <summary>
        /// 获取随机数
        /// </summary>
        /// <returns></returns>
        private int GetNonce()
        {
            var random = new Random();
            int nonce = random.Next(1, Int32.MaxValue);
            return nonce;
        }
    }
}
