using System;
using System.Data;
using System.IO;

namespace Orciid.Media.Util
{
	public class CsvWriter
	{
		public static string WriteToString(DataTable table, bool header, bool quoteall)
		{
			return WriteToString(table, header, quoteall, ',');
		}

		public static string WriteToString(DataTable table, bool header, bool quoteall, 
			char separator)
		{
			StringWriter writer = new StringWriter();
			WriteToStream(writer, table, header, quoteall, separator);
			return writer.ToString();
		}

		public static void WriteToStream(TextWriter stream, DataTable table, bool header, 
			bool quoteall)
		{
			WriteToStream(stream, table, header, quoteall, ',');
		}

		public static void WriteToStream(TextWriter stream, DataTable table, bool header, 
			bool quoteall, char separator)
		{
			if (header)
			{
				for (int i = 0; i < table.Columns.Count; i++)
				{
					WriteItem(stream, table.Columns[i].Caption, quoteall, separator);
					if (i < table.Columns.Count - 1)
						stream.Write(separator);
					else
						stream.Write('\n');
				}
			}
			foreach (DataRow row in table.Rows)
			{
				for (int i = 0; i < table.Columns.Count; i++)
				{
					WriteItem(stream, row[i], quoteall, separator);
					if (i < table.Columns.Count - 1)
						stream.Write(separator);
					else
						stream.Write('\n');
				}
			}
		}

		private static void WriteItem(TextWriter stream, object item, bool quoteall,
			char separator)
		{
			if (item == null)
				return;
			string s = item.ToString();
			if (quoteall || s.IndexOfAny(new char[] { '"', '\x0A', '\x0D', separator }) > -1)
				stream.Write("\"" + s.Replace("\"", "\"\"") + "\"");
			else
				stream.Write(s);
		}
	}
}
