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

namespace Knoks.CryptoExchanges.ExchangeClients
{
    class BinanceExchange : IExchangeContainer
    {
        #region Members
        private WebSocket4NetSocket socket;
        private BinanceClient client;
        private UpdateData saveDataEvent;
        private int exchangeId;
        public IDictionary<string, string> ReplaceSymbols { get; set; }
        #endregion

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="exchangeId"></param>
        public BinanceExchange(int exchangeId) {
            this.exchangeId = exchangeId;
        }

        public async Task InitClient(UpdateData updateData) {
            this.saveDataEvent = updateData;
            await Task.CompletedTask;
        }
        
        public async Task RequestPairsData(List<Tuple<string, string>> pairs) {
            socket = new BinanceWebsocket4Net();
            var streams = string.Join("/", pairs.Select(x => $"{x.Item1}{x.Item2}@kline_1m").ToArray()).TrimStart('/');
            socket.Create($"wss://stream.binance.com:9443/stream?streams={streams.ToLower()}"); // depth10 // wss://stream.binance.com:9443/ws/bnbbtc@depth");
            socket.Sign((s) => new ConsoleWebClient(
                saveDataEvent, 
                this.exchangeId, 
                (ss) =>
                {
                    return client = new BinanceClient(ss);
                }, s));

            await socket.Connect();
        }

        public async Task CloseConnection() {
            await socket.Close();
        }

        public async Task Reconnect(){
            await socket.Close();
        }
    }
}
