
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Globalization;

namespace WijMarket.Models
{
    /// <summary>
    /// Summary description for Stock
    /// </summary>
    public class Stock
    {
        public Stock()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public string Symbol { get; set; }
        public string Name { get; set; }
        public float Open { get; set; }
        public float Close { get; set; }
        public float High { get; set; }
        public float Low { get; set; }
        public float Volume { get; set; }
        public bool Valid { get; set; }
        //public DateTime Date { get; set; }
        public string DateString { get; set; }
    }
    public class Stocks
    {
        public static List<Stock> GetStocks(string Symbols)
        {
            List<Stock> lst = new List<Stock>();
            var fmt = "https://marketdata.websol.barchart.com/getQuote.csv?apikey={0}&symbols={1}&fields={2}&mode=I&jerq=false";
            var token = "f75c082171ff05d8b2588de998ff034c";
            var fields = "ask,bid";
            // api key 0: the api key from https://www.barchart.com/ondemand
            // symbols 1:A symbol or code that identifies a financial instrument. Multiple symbols separated by a comma may be used.
            // fields 2: the fields requested
            var url = string.Format(fmt, token, Symbols, fields);

            // get content
            var sb = new StringBuilder();
            var wc = new WebClient();

            IWebProxy defaultProxy = WebRequest.DefaultWebProxy;
            if (defaultProxy != null)
            {
                defaultProxy.Credentials = CredentialCache.DefaultCredentials;
                wc.Proxy = defaultProxy;
            }

            using (var sr = new StreamReader(wc.OpenRead(url)))
            {
                // skip headers
                var header = sr.ReadLine();
                var headers = new List<string>(header.Split(','));

                int i = 0;
                // read each line
                for (var line = sr.ReadLine(); line != null; line = sr.ReadLine())
                {
                    var items = line.Split(',').Select(item => item.Trim('"')).ToArray();

                    var stock = new Stock();
                    stock.Symbol = items[headers.IndexOf("symbol")];
                    stock.Name = items[headers.IndexOf("name")];
                    stock.Open = ParseFloat(items[headers.IndexOf("open")]); // as requested
                    stock.Close = ParseFloat(items[headers.IndexOf("close")]); // as requested
                    stock.High = ParseFloat(items[headers.IndexOf("high")]);
                    stock.Low = ParseFloat(items[headers.IndexOf("low")]);
                    stock.Volume = ParseFloat(items[headers.IndexOf("volume")]);
                    lst.Add(stock);
                }
            }

            return lst;
        }

        public static List<Stock> GetStockHistory(string symbol, DateTime startDate, DateTime endDate, string interval)
        {
            List<Stock> list = new List<Stock>();

            var fmt = "https://www.quandl.com/api/v3/datasets/WIKI/{0}.csv?auth_token={1}&start_date={2}&end_date={3}";
            // 0: stock symbol
            // auth_token 1: token
            // start_date 2: date yyyy-MM-dd
            // auth_token 3: date yyyy-MM-dd
            var token = "n5zwD2oCokRjh96x_yxV";
            var url = string.Format(fmt, symbol, token, startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"));

            // get content
            var sb = new StringBuilder();
            var wc = new WebClient();

            IWebProxy defaultProxy = WebRequest.DefaultWebProxy;
            if (defaultProxy != null)
            {
                defaultProxy.Credentials = CredentialCache.DefaultCredentials;
                wc.Proxy = defaultProxy;
            }

            using (var sr = new StreamReader(wc.OpenRead(url)))
            {
                // skip headers
                sr.ReadLine();

                // read each line
                for (var line = sr.ReadLine(); line != null; line = sr.ReadLine())
                {
                    var items = line.Split(',');

                    var stock = new Stock();
                    stock.Open = float.Parse(items[1], CultureInfo.InvariantCulture);
                    stock.Close = float.Parse(items[4], CultureInfo.InvariantCulture);
                    stock.High = float.Parse(items[2], CultureInfo.InvariantCulture);
                    stock.Low = float.Parse(items[3], CultureInfo.InvariantCulture);
                    stock.Volume = float.Parse(items[5], CultureInfo.InvariantCulture);
                    stock.Valid = true;
                    stock.Symbol = symbol;
                    stock.DateString = DateTime.Parse(items[0], CultureInfo.InvariantCulture).ToString(@"MM'/'dd'/'yyyy");

                    list.Add(stock);
                }
            }

            return list;
        }

        private static float ParseFloat(string from)
        {
            float to;
            if (float.TryParse(from, out to))
            {
                return to;
            }
            return 0f;
        }

        private static double ParseDouble(string from)
        {
            double to;
            if (double.TryParse(from, out to))
            {
                return to;
            }
            return 0d;
        }
    }
}