using System;
using System.Text;
using System.Collections.Generic;

namespace MarketData.Utils
{
  public class CSVLineHelper
  {
	  public CSVLineHelper()
	  {
	  }
    public static String[] ParseLine(String strLine)
    {
      try
      {
        List<String> items = new List<String>();
        int length = strLine.Length;
        for (int index = 0; index < length; index++)
        {
          char ch = strLine[index];
          if (ch == '"') items.Add(GetQuotedItem(strLine, ref index, length));
          else items.Add(GetItem(strLine, ref index, length));
        }
        return items.ToArray();
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
        return null;
      }
    }
    private static String GetQuotedItem(String strLine,ref int index,int length)
    {
      StringBuilder sb = new StringBuilder();
      char ch = '\0';
      while (index<length)
      {
        ch = strLine[++index];
        if (ch == '"') { index++; break; }
        if (ch != ',') sb.Append(ch);
      }
      return sb.ToString();
    }
    private static String GetItem(String strLine, ref int index, int length)
    {
      StringBuilder sb = new StringBuilder();
      char ch='\0';
      while (ch != ',' && index<length)
      {
        ch = strLine[index++];
        if (ch != ',') sb.Append(ch);
      }
      index--;
      return sb.ToString();
    }
  }
}