using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MarketData.MarketDataModel;
using MarketData.DataAccess;
using MarketData.Utils;

namespace MarketData.Helper
{
  public class HistoricalMarketDataHelper
  {
    private static int MaxThreads = (int)ThreadHelperEnum.MaxThreads;
    private List<String> symbols;
    private int currentIndex = 0;

    public HistoricalMarketDataHelper()
    {
    }
		public bool LoadHistorical(String symbol)
		{
			Profiler profiler=new Profiler();
			try
			{
				symbols = new List<String>();
				symbols.Add(symbol);
				currentIndex = 0;
				while (true)
				{
					List<String> queueSymbols = GetQueueSymbols();
					if (null == queueSymbols || 0 == queueSymbols.Count) break;
					ManualResetEvent[] resetEvents = new ManualResetEvent[queueSymbols.Count];
					for (int eventIndex = 0; eventIndex < resetEvents.Length; eventIndex++)
					{
						resetEvents[eventIndex] = new ManualResetEvent(false);
					}
					for (int index = 0; index < queueSymbols.Count; index++)
					{
						ThreadHelper threadHelper = new ThreadHelper(queueSymbols[index],resetEvents[index]);
						ThreadPool.QueueUserWorkItem(ThreadPoolCallbackLoadHistorical, threadHelper);
					}
					MDTrace.WriteLine(LogLevel.DEBUG,"Load Historical, waiting for queued items to complete.");
					WaitHandle.WaitAll(resetEvents);
				}
				return true;
			}
			finally
			{
				MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[LoadHistorical]End, total took {0}(ms)",profiler.End()));
			}
		}
		public bool LoadHistorical()
		{
			Profiler profiler=new Profiler();
			try
			{
				symbols = PricingDA.GetSymbols();
				currentIndex = 0;
				while (true)
				{
					List<String> queueSymbols = GetQueueSymbols();
					if (null == queueSymbols || 0 == queueSymbols.Count) break;
					ManualResetEvent[] resetEvents = new ManualResetEvent[queueSymbols.Count];
					for (int eventIndex = 0; eventIndex < resetEvents.Length; eventIndex++)
					{
						resetEvents[eventIndex] = new ManualResetEvent(false);
					}
					for (int index = 0; index < queueSymbols.Count; index++)
					{
						ThreadHelper threadHelper = new ThreadHelper(queueSymbols[index],resetEvents[index]);
						ThreadPool.QueueUserWorkItem(ThreadPoolCallbackLoadHistorical, threadHelper);
					}
					MDTrace.WriteLine(LogLevel.DEBUG,"Load Historical, waiting for queued items to complete.");
					WaitHandle.WaitAll(resetEvents);
				}
				return true;
			}
			finally
			{
				MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[LoadHistorical]End, total took {0}(ms)",profiler.End()));
			}
		}
    private List<String> GetQueueSymbols()
    {
      List<String> queueSymbols = new List<String>();
      int index = currentIndex;
      for (; index < currentIndex + MaxThreads && index < symbols.Count; index++)
      {
        queueSymbols.Add(symbols[index]);
      }
      currentIndex = index;
      return queueSymbols;
    }
    public void ThreadPoolCallbackLoadHistorical(Object threadHelperContext)
    {
      ThreadHelper threadHelper = (ThreadHelper)threadHelperContext;
			try
			{
				MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Load Historical, Thread {0} started for {1}...", Thread.CurrentThread.ManagedThreadId, threadHelper.Symbol));
				LoadHistoricalEx(threadHelper.Symbol);
				MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Load Historical, Thread {0} ended for {1}", Thread.CurrentThread.ManagedThreadId, threadHelper.Symbol));
			}
			finally
			{
			  threadHelper.ResetEvent.Set();
			}
    }
    public static void LoadHistoricalEx(String symbol)
    {
      MDTrace.WriteLine(LogLevel.DEBUG,"Loading time series data values for '" + symbol + "'");
      Dictionary<TimeSeriesElement.ElementType, TimeSeriesCollection> timeSeriesCollection = MarketDataHelper.GetHistoricalValues(symbol);
      if (null == timeSeriesCollection || 0 == timeSeriesCollection.Count)
      {
        return;
      }
      List<TimeSeriesElement.ElementType> keys=new List<TimeSeriesElement.ElementType>(timeSeriesCollection.Keys);
      for (int cIndex = 0; cIndex < keys.Count; cIndex++)
      {
        TimeSeriesCollection timeSeriesElements = timeSeriesCollection[keys[cIndex]];
        if (null == timeSeriesElements || 0 == timeSeriesElements.Count)
        {
          MDTrace.WriteLine(LogLevel.DEBUG,"Unable to retrieve time series values for '" + symbol + "'");
          continue;
        }
        HistoricalDA.InsertTimeSeries(timeSeriesElements);
      }
    }
  }
}

