using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MarketData.MarketDataModel;
using PortfolioManager.ViewModels;
using MarketData.Utils;

namespace PortfolioManager.Extensions
{
  public static class StopLimitsExtensions
  {
    public static StopLimits FromSaveParams(SaveParameters saveParameters)
    {
      StopLimits stopLimits=new StopLimits();
      int stopHistoryCount=int.Parse((from KeyValuePair<String,String> item in saveParameters where item.Key.Equals("StopHistoryCount") select item).FirstOrDefault().Value);
      for(int index=0;index<stopHistoryCount;index++)
      {
        String strItemKey=String.Format("StopHistory_{0}",index);
        String strStopHistoryItem=(from KeyValuePair<String,String> item in saveParameters where item.Key.Equals(strItemKey) select item).FirstOrDefault().Value;
        NVPCollection nvpCollection=new NVPCollection(strStopHistoryItem);
        StopLimit stopLimit=MarketData.MarketDataModel.StopLimit.FromNVPCollection(nvpCollection);
        stopLimits.Add(stopLimit);
      }
      stopLimits=new StopLimits(stopLimits.OrderBy(x => x.EffectiveDate).ToList());
      return stopLimits;
    }

    public static SaveParameters FromStopLimits(this StopLimits stopLimits)
    {
      StringBuilder sb = new StringBuilder();
      if(null==stopLimits || 0==stopLimits.Count)return new SaveParameters();
      NVPCollections nvpCollections = stopLimits.ToNVPCollections();
      sb.Append("StopHistoryCount").Append(",").Append(String.Format("{0}", nvpCollections.Count)).Append(",");
      for (int index = 0; index < nvpCollections.Count; index++)
      {
        sb.Append(String.Format("StopHistory_{0}", index)).Append(",").Append(nvpCollections[index].ToString());
        if (index < nvpCollections.Count - 1) sb.Append(",");
      }
      return SaveParameters.Parse(sb.ToString());
    }
  }
}



