using System;
using System.Collections.Generic;

namespace MarketData.MarketDataModel
{
  public class ReturnItemComparerDesc : IComparer<ReturnItem>
  {
    public int Compare(ReturnItem r1, ReturnItem r2)
    {
      if (r1.Date > r2.Date) return -1;
      else if (r1.Date < r2.Date) return 1;
      return 0;
    }
  }
  public class ReturnItems : List<ReturnItem>
  {
    public ReturnItems()
    {
    }
    public ReturnItems(TimeSeriesCollection timeSeriesCollection)
    {
      for (int index = 0; index < timeSeriesCollection.Count; index++)
      {
        TimeSeriesElement timeSeriesElement = timeSeriesCollection[index];
        ReturnItem returnItem = new ReturnItem();
        returnItem.Date = timeSeriesElement.AsOf;
        returnItem.Value = timeSeriesElement.Value;
        Add(returnItem);
      }
      CalculateReturns();
    }
    public void CalculateReturns()
    {
      Sort(new ReturnItemComparerDesc());
      for (int index = Count - 2; index >= 0; index--)
      {
        ReturnItem returnItem = this[index];
        double currentPrice = this[index].Value;
        double prevPrice = this[index + 1].Value;
        if (prevPrice == 0.00) returnItem.Return = 0.00;
        else returnItem.Return = ((currentPrice - prevPrice) / Math.Abs(prevPrice));
      }
    }
    public void SortItems()
    {
      Sort(new ReturnItemComparerDesc());
    }
    public float[] ToFloat()
    {
      List<float> list = new List<float>();
      for (int index = 0; index < Count-1; index++) // the last item will always be zero
      {
        list.Add((float)this[index].Return);
      }
      return list.ToArray();
    }
  }
  public class ReturnItem
  {
    public ReturnItem()
    {
    }
    public ReturnItem(DateTime date, double value)
    {
      Date = date;
      Value = value;
    }
    public DateTime Date { get; set; }
    public double Value { get; set; }
    public double Return { get; set; }
  }
}
