using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace InvExplorer.Web
{
    /// <summary>
    /// Random stock info provider.
    /// </summary>
    /// <remarks>
    /// The random generator is seeded with the asset symbol, so calling this multiple times
    /// for the same symbol will yield the same results.
    /// The generator is a random walk with a slight tendency to decrease from the initial 
    /// price as we progress into the past.
    /// </remarks>
    public class RandomAssetInfoProvider : IAssetIInfoProvider
    {
        static List<SymbolName> _symbolNames;

        // ** IAssetIInfoProvider
        public List<double> GetCurrentPrice(string symbol)
        {
            var currChange = new List<double>();
            var prices = GetAssetPrices(symbol, DateTime.Today.AddDays(-5), DateTime.Today);
            if (prices.Count > 1)
            {
                currChange.Add(prices[prices.Count - 1].Price);
                currChange.Add(prices[prices.Count - 2].Price - currChange[0]);
            }
            return currChange;
        }
        public List<AssetPrice> GetAssetPrices(string symbol, DateTime start, DateTime end)
        {
            var list = new List<AssetPrice>();

            var rnd = new Random(symbol.GetHashCode());
            var price = GetNormal(rnd, 500);
            for (var dt = DateTime.Today; dt >= start; dt = dt.AddDays(-1))
            {
                if (dt >= start && dt <= end)
                {
                    var sp = new AssetPrice();
                    sp.Date = dt;
                    sp.Price = price;
                    list.Add(sp);
                }
                var delta = price * ((rnd.NextDouble() * .04) - 0.0199);
                price = Math.Max(0, price - delta);
            }

            return list;
        }
        public List<SymbolName> GetAssetSymbolNames()
        {
            if (_symbolNames == null)
            {
                _symbolNames = SymbolName.LoadSymbolNames();
            }
            return _symbolNames;
        }

        // implementation
        double GetNormal(Random rnd, double avg)
        {
            var cnt = 5;
            double value = 0;
            for (int i = 0; i < cnt; i++)
            {
                value += rnd.NextDouble() * avg / cnt;
            }
            return value;
        }
    }
}