using Knoks.Core.Entities;
using Knoks.Core.Logic.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Knoks.Core.Exchanges
{
    public class CexExchange : IExchange
    {
        private ExchangeSettings settings;

        public CexExchange(ExchangeSettings settings)
        {
            this.settings = settings;
            this.settings.ApiUrl = settings.ApiUrl ?? "https://cex.io/api/";
        }
        public async Task<IEnumerable<Ticker>> GetMarkets()
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(settings.ApiUrl + "currency_limits");
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsJsonAsync<CexResponse>();

                return data.Data.Pairs.Where(s => settings.AllowedCurrencies.Contains(s.Symbol2.ToUpper())).
                    Select(it => new Ticker() { TickerDisplayName = $"{it.Symbol1}/{it.Symbol2}", Currency1 = Replace(it.Symbol1), Currency2 = Replace(it.Symbol2), Currency = Replace(it.Symbol1), TickerSymbol = $"{it.Symbol1}{it.Symbol2}" });
            }
            throw new NotSupportedException("Cex error");
        }

        public async Task<TickerData> GetTickerData(TickerInfo ticker, DateTime start, DateTime end)
        {
            //https://cex.io/api/ticker/{Currency1}/{Currency2}
            HttpClient client = new HttpClient();
            var response = await client.GetAsync($"{settings.ApiUrl}ticker/{ticker.Currency1}/{ticker.Currency2}");
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsJsonAsync<TickerType>();

                return new TickerData()
                {
                    TickerTime = ConvertFromLong(data.Timestamp),
                    TickerId = ticker.TickerId,
                    Open = data.Low,
                    High = data.High,
                    Low = data.Low,
                    Close = data.Last,
                    Volume = data.Volume
                };
            }
            throw new NotSupportedException("CEX error");
        }

        internal class TickerType
        {
            public object this[string propertyName]
            {
                get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
                set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
            }
            public decimal Low { get; set; }
            public decimal High { get; set; }
            public decimal Last { get; set; }
            public decimal Volume { get; set; }
            public long Timestamp { get; set; }
            /*
              "volume30d": "81150.14153359",
              "bid": 17400.04,
              "ask": 17418.2
             */
        }

        private long ConvertToLong(DateTime time)
        {
            return (long)(time - Constants._1970Time).TotalMilliseconds;
        }

        private DateTime ConvertFromLong(long ms)
        {
            return Constants._1970Time.AddMilliseconds(ms);
        }

        private string Replace(string asset)
        {
            if (settings.ReplaceSymbols != null && settings.ReplaceSymbols.ContainsKey(asset))
            {
                return settings.ReplaceSymbols[asset];
            }
            return asset;
        }
    }
    
    
}
