using Knoks.Core.Entities;
using Knoks.Core.Logic.Interfaces;
using Newtonsoft.Json;
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 BittrexExchange : IExchange
    {
        private ExchangeSettings settings;

        public BittrexExchange(ExchangeSettings settings)
        {
            this.settings = settings;
            this.settings.ApiUrl = settings.ApiUrl ?? "https://bittrex.com/api/";
        }
        public async Task<IEnumerable<Ticker>> GetMarkets()
        {
            HttpClient client = new HttpClient();            
            HttpResponseMessage response = await client.GetAsync(settings.ApiUrl + "v1.1/public/getmarkets");//https://bittrex.com/api/v1.1/public/getmarkets
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsJsonAsync<BittrexResponse>();
                return data.Result.Where(s => settings.AllowedCurrencies.Contains(s.BaseCurrency.ToUpper()))
                    .Select(it => new Ticker()
                    {
                        TickerDisplayName = $"{it.MarketCurrency}/{it.BaseCurrency}", //it.MarketName.Replace("-", "/"),
                        Currency1 = it.MarketCurrency,
                        Currency2 = it.BaseCurrency,
                        Currency = it.BaseCurrency,
                        TickerSymbol = $"{it.MarketCurrency}{it.BaseCurrency}" //it.MarketName.Replace("-", string.Empty)
                    });//Active
            }
            throw new NotSupportedException("Bittrex error");
        }

        public async Task<TickerData> GetTickerData(TickerInfo ticker, DateTime start, DateTime end)
        {
            //https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-ltc
            HttpClient client = new HttpClient();
            var response = await client.GetAsync($"{settings.ApiUrl}v1.1/public/getmarketsummary?market={ticker.Currency2}-{ticker.Currency1}");
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsJsonAsync<TickerType>();

                return new TickerData()
                {
                    TickerTime = data.Result[0].Timestamp,
                    TickerId = ticker.TickerId,
                    Open = data.Result[0].Low,
                    High = data.Result[0].High,
                    Low = data.Result[0].Low,
                    Close = data.Result[0].Last,
                    Volume = data.Result[0].Volume
                };
            }
            throw new NotSupportedException("Bittrex error");
        }

        internal class TickerTypeResult {
            public decimal High { get; set; }
            public decimal Low { get; set; }
			public decimal Volume { get; set; }
            public decimal Last { get; set; }
			public DateTime Timestamp { get; set; }  //"2014-07-09T07:22:16.72",
            //"BaseVolume" : 47.03987026,
            //MarketName" : "BTC-LTC",
            //"Bid" : 0.01271001,
            //"Ask" : 0.01291100,
            //"OpenBuyOrders" : 45,
            //"OpenSellOrders" : 45,
            //"PrevDay" : 0.01229501,
            //"Created" : "2014-02-13T00:00:00",
            //"DisplayMarketName" : null
        }

        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 bool Success { get; set; }
            public string Message { get; set; }
            public TickerTypeResult[] Result { get; set; }
        }

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

        //private string ReplaceToAsset(string value)
        //{
        //    var replaceToAsset = settings.ReplaceSymbols.FirstOrDefault(x => x.Value == value);
        //    if (!replaceToAsset.Equals(default(KeyValuePair<string, string>)))
        //    {
        //        return replaceToAsset.Key;
        //    }
        //    return value;
        //}
    }
    
    
}
