using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;

namespace MvcExplorer.Models
{
    //FaceBook inc. finance data.
    public static class FbData
    {
        private static List<FinanceData> _jsonData;
        public static List<FinanceData> GetDataFromJson()
        {
            if (_jsonData != null)
            {
                return _jsonData;
            }

            string jsonText = new StreamReader(GetJsonStream("fb.json")).ReadToEnd();
            JArray ja = (JArray)JsonConvert.DeserializeObject(jsonText);
            List<FinanceData> list = new List<FinanceData>();
            foreach (var obj in ja)
            {
                string date = obj["date"].ToString();
                double high = Convert.ToDouble(obj["high"].ToString());
                double low = Convert.ToDouble(obj["low"].ToString());
                double open = Convert.ToDouble(obj["open"].ToString());
                double close = Convert.ToDouble(obj["close"].ToString());
                double volume = Convert.ToDouble(obj["volume"].ToString());
                list.Add(new FinanceData { X = DateTime.ParseExact(date, "MM/dd/yy", CultureInfo.InvariantCulture), High = high, Low = low, Open = open, Close = close, Volume = volume });
            }
            _jsonData = list;
            return list;
        }

        public static Stream GetJsonStream(string name)
        {
            var assembly = typeof(FbData).GetTypeInfo().Assembly;
            var ress = assembly.GetManifestResourceNames();
            var res = assembly.GetManifestResourceNames().Where(resName => resName.Contains(name)).ToList();
            if (res.Count == 0)
            {
                throw new ArgumentException(string.Format("Cannot find {0} from assembly resources.", name));
            }
            return assembly.GetManifestResourceStream(res[0]);
        }
    }
}
