using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;
using System.Collections.Generic;

namespace MarketData.Utils
{
  public class NVPDictionary : Dictionary<String,NVP>
  {
    public NVPDictionary()
    {
    }
  }
  public class NVPCollections : List<NVPCollection>
  {
    public NVPCollections()
    {
    }
    public NVPCollections(List<String> nvpCollections)
    {
      foreach(String nvpCollectionString in nvpCollections)Add(new NVPCollection(nvpCollectionString));
    }
    public List<String> ToList()
    {
      List<String> nvpCollections=new List<String>();
      foreach(NVPCollection nvpCollection in this)nvpCollections.Add(nvpCollection.ToString());
      return nvpCollections;
    }
  }
  public class NVPCollection : List<NVP>
  {
    public NVPCollection()
    {
    }
    public NVPCollection(String nvpCollectionString)
    {
      if(null==nvpCollectionString)return;
      String[] nvpItems=nvpCollectionString.Split('|');
      if(null==nvpItems)return;
      for(int index=0;index<nvpItems.Length;index++)
      {
        Add(new NVP(nvpItems[index]));
      }
    }
    public NVPDictionary ToDictionary()
    {
      NVPDictionary dict=new NVPDictionary();
      foreach(NVP nvp in this)dict.Add(nvp.Name,nvp);
      return dict;
    }
    public static NVPCollection FromString(String strNVPCollection)
    {
      return new NVPCollection(strNVPCollection);
    }
    public override String ToString()
    {
      StringBuilder sb=new StringBuilder();
      for(int index=0;index<Count;index++)
      {
        NVP nvp=this[index];
        sb.Append(nvp.ToString());
        if(index<Count-1)sb.Append("|");
      }
      return sb.ToString();
    }
  }
  public class NVP
  {
    public NVP(String name,String value)
    {
      Name=name;
      Value=value;
    }
// This needs to work with nvpString assignment that contains embedded '=' signs.  For example Expression=a=1;b=2.   Name="Expression", Value="a=1;b=2"
    public NVP(String nvpString)
    {
      if(null==nvpString)return;
      String[] nvps=nvpString.Split('=');
			if(nvps.Length<2)return;
      Name=nvps[0].Trim();
			if(2==nvps.Length)Value=nvps[1].Trim();
			else
			{
				StringBuilder sb=new StringBuilder();
				for(int itemIndex=1;itemIndex<nvps.Length;itemIndex++)
				{
				  sb.Append(nvps[itemIndex]);
					if(itemIndex<nvps.Length-1)sb.Append("=");
				}
				Value=sb.ToString();
			}
    }
    public T Get<T>()
    {
      T result=default(T);
      try {result = (T)Convert.ChangeType(Value, typeof(T));}
      catch {result = default(T);}
      return result;
    }
    public String Name{get;set;}
    public String Value{get;set;}
    public override String ToString()
    {
      StringBuilder sb=new StringBuilder();
      sb.Append(Name).Append("=").Append(Value);
      return sb.ToString();
    }
  }
}