using BinanceExchange.API.Client;
using BinanceExchange.API.Enums;
using BinanceExchange.API.Models.Request;
using BinanceExchange.API.Models.Response;
using BinanceExchange.API.Models.WebSocket;
using BinanceExchange.API.Websockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace SignalsTest
{


    public class CoinWatch
    {
        public string pair;
        public KlineInterval interval;
        public List<KlineCandleStickResponse> candles=new List<KlineCandleStickResponse>();
        public event EventHandler<BinanceTradeData> PriceUpdated;

        public CoinWatch(string pair)
        {
            this.pair = pair;
            Init();
        }

        void Init()
        {
          //  InitLivestream();
            KeepUpdatingCandles();
         // TestCallbacks();
        }

        async void TestCallbacks()
        {
            while (true)
            {
                await Task.Delay(1000);
                PriceUpdated?.Invoke(this, new BinanceTradeData() { BestAskPrice=0 });
            }
        }

        async Task UpdateCandles()
        {
            GetKlinesCandlesticksRequest req = new GetKlinesCandlesticksRequest();
            req.Interval = BinanceExchange.API.Enums.KlineInterval.FifteenMinutes;
            req.Symbol = pair;
            req.EndTime = DateTime.Now;
            req.Limit = 100;

            candles = await Brian.Client.GetKlinesCandlesticks(req);
            int[] mas = new int[] { 7, 12, 25 };
            TAReport report = TAReport.Generate(candles, candles.Count-1, mas, mas);
            await Messenger.instance.SendMessage(report.toJson());
            Console.WriteLine("Updated candles, last candle closed at " + candles[candles.Count - 1].CloseTime);
        }

        async void KeepUpdatingCandles()
        {
            UpdateCandles();
            while(true)
            {
                await Task.Delay(60000);
                if (DateTime.Now.Minute % Utils.GetMinutesForInterval(interval) == 0) { UpdateCandles(); }
            }
        }

        void InitLivestream()
        {
            var manualWebsocket = new InstanceBinanceWebSocketClient(Brian.Client);
            var socketId = manualWebsocket.ConnectToIndividualSymbolTickerWebSocket(pair, data =>
            {
                candles[candles.Count - 1].Close = data.BestAskPrice;
                
            });
        }
    }
}
