using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using WebSocket.Interfaces;

namespace WebSocket.Clients
{
    public class OKExWebsocket4Net : WebSocket4NetSocket
    {
        #region Members
        private Timer Timer;
        private DateTime? LastCall;
        private DateTime? CreateTime;
        #endregion

        /// <summary>
        /// ctor
        /// </summary>
        public OKExWebsocket4Net() {
        }

        public override void Create(string url)
        {
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
            //ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true;
            base.Create(url);
            //Socket.EnableAutoSendPing = false;
            Socket.MessageReceived += Socket_MessageReceived;
            CreateTime = DateTime.Now;
        }

        private void Socket_MessageReceived(object sender, WebSocket4Net.MessageReceivedEventArgs e)
        {
            LastCall = DateTime.Now;
        }

        public async override Task Connect()
        {
            await base.Connect();
            Timer = new Timer((obj) => SpecialTick(), null, 16000, 16000);
        }

        private void SpecialTick()
        {
            DateTime? lastCall = new List<DateTime?>() { Socket.LastActiveTime, LastCall, CreateTime }.Where(it => it.HasValue && it != DateTime.MinValue).Max();
            if (lastCall == null || DateTime.Now - lastCall > TimeSpan.FromSeconds(15))//15 - by auto tick
            {
                OnTick();
            }
        }

        public override Task Close()
        {
            return base.Close();
        }
    }
}
