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

namespace MarketData.Helper
{  public class SplitHelper
  {
//  I have found that simply reloading prices with splits from Yahoo solves the issue of corporate actions as they are handled on Yahoo Finanace
    public static bool ProcessSplits(Splits splits)
    {
      foreach(Split split in splits)ProcessSplit(split.Symbol);
      return true;
    }
    public static bool ProcessSplit(String symbol)
    {
      Splits splits=SplitsDA.GetSplits(symbol);
      if(null==splits||0==splits.Count)return false;
      DateGenerator dateGenerator=new DateGenerator();

      for(int index=0;index<splits.Count;index++)
      {
        Split split=splits[index];

        if(!PricingDA.SecurityExists(split.Symbol))
        {
          MDTrace.WriteLine(LogLevel.DEBUG,String.Format("No security detail for {0}",split.Symbol));
          continue;
        }
        Prices prices=PricingDA.GetPrices(split.Symbol);
        if(null==prices||0==prices.Count)continue;
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Reloading prices for {0}",split.Symbol));
        Prices marketPrices=MarketDataHelper.GetDailyPrices(split.Symbol,prices[prices.Count-1].Date,prices[0].Date);
        if(null==marketPrices||0==marketPrices.Count)
        {
          MDTrace.WriteLine(LogLevel.DEBUG,String.Format("No prices for {0} from {1} to {2}",split.Symbol,Utility.DateTimeToStringMMHDDHYYYY(prices[prices.Count-1].Date),Utility.DateTimeToStringMMHDDHYYYY(prices[0].Date)));
          continue;
        }
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Inserting prices for {0}",split.Symbol));
        PricingDA.InsertPrices(marketPrices);
        split.Applied=true;
        split.AppliedLeastRecent=marketPrices[marketPrices.Count-1].Date;
        split.AppliedMostRecent=marketPrices[0].Date;
        MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Updating split status for {0}",split.Symbol));
        SplitsDA.UpdateSplit(split);
      }
      return true;
    }
  }
}

