// define this symbol to use Google Finance services (instead of random data)
//#define USE_GOOGLE_FINANCE
#define USE_YAHOO_FINANCE

using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Diagnostics;

namespace InvExplorer.Web
{
    [ServiceContract(Namespace = "")]
    [SilverlightFaultBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1
    {
#if USE_GOOGLE_FINANCE
        static IAssetIInfoProvider _assetPriceProvider = new GoogleAssetInfoProvider();
#elif USE_YAHOO_FINANCE
        static IAssetIInfoProvider _assetPriceProvider = new YahooAssetInfoProvider();
#elif USE_ALCATRAZ
        static IAssetIInfoProvider _assetPriceProvider = new AlcatrazAssetInfoProvider();
#else // Random
        static IAssetIInfoProvider _assetPriceProvider = new RandomAssetInfoProvider();
#endif
        // Add operations here and mark them with [OperationContract]
        // (so they will be converted in to WebServices)

        [OperationContract]
        public Asset GetAsset(string symbol)
        {
            // create new asset
            var a = new Asset();
            a.Symbol = symbol;
            a.AssetType = AssetType.Stock;

            // get asset name from symbol
            var list = _assetPriceProvider.GetAssetSymbolNames();
            var sn = new SymbolName();
            sn.Symbol = symbol;
            int index = list.BinarySearch(sn);
            a.Name = index >= 0 ? list[index].Name : "?";

            // get other asset info
            var price = _assetPriceProvider.GetCurrentPrice(symbol);
            if (price != null && price.Count > 1)
            {
                a.LastPrice = price[0];
                a.Change = price[1];
            }

            // return new asset
            return a;
        }

        [OperationContract]
        public List<SymbolName> GetAssetSymbolNames(int start, int count)
        {
            // get all symbols
            var all = _assetPriceProvider.GetAssetSymbolNames();

            // return part that was requested
            var list = new List<SymbolName>();
            for (int i = start; i < start + count && i < all.Count; i++)
            {
                list.Add(all[i]);
            }

            // done
            return list;
        }

        [OperationContract]
        public List<AssetPrice> GetAssetPrices(string symbol)
        {
            // get last 5 years worth of data
            var end = DateTime.Today;
            var start = new DateTime(end.Year - 5, 1, 1);
            return _assetPriceProvider.GetAssetPrices(symbol, start, end);
        }
    }
}
