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 CIKMarketDataHelper
  {
    private static int MaxThreads = (int)ThreadHelperEnum.MaxThreads;
    private List<String> symbols;
    private int currentIndex = 0;

    public CIKMarketDataHelper()
    {
    }
		public bool UpdateAllMissingCIK()
		{
			Profiler profiler=new Profiler();
			try
			{
				symbols = PricingDA.GetSymbolsForNullCIK();
				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 cikThreadHelper = new ThreadHelper(queueSymbols[index],resetEvents[index]);
						ThreadPool.QueueUserWorkItem(ThreadPoolCallbackUpdateMissingCIK, cikThreadHelper);
					}
					MDTrace.WriteLine(LogLevel.DEBUG,"Load CIK, waiting for queued items to complete.");
					WaitHandle.WaitAll(resetEvents);
				}
				return true;
			}
			finally
			{
				MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[UpdateAllMissingCIK]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 ThreadPoolCallbackUpdateMissingCIK(Object threadHelperContext)
    {
      ThreadHelper threadHelper = (ThreadHelper)threadHelperContext;
			try
			{
				MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Load CIK, Thread {0} started for {1}...", Thread.CurrentThread.ManagedThreadId, threadHelper.Symbol));
				UpdateMissingCIKEx(threadHelper.Symbol);
				MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Load CIK, Thread {0} ended for {1}", Thread.CurrentThread.ManagedThreadId, threadHelper.Symbol));
			}
			finally
			{
			  threadHelper.ResetEvent.Set();
			}
    }
    public static void UpdateMissingCIKEx(String symbol)
    {
      DateGenerator dateGenerator = new DateGenerator();
      String cik = MarketDataHelper.GetCIK(symbol);
      if (null == cik)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("No CIK for symbol {0}",symbol));
        return;
      }
      MDTrace.WriteLine(LogLevel.DEBUG,String.Format("CIK for symbol {0}={1}",symbol,cik));
      PricingDA.UpdateCIKForSymbol(symbol, cik);
    }
  }
}

