using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace QC.CTDS.DM.SharedLibrary;

public class DelimiterWriter
{
	private StreamWriter _streamWriter;

	private string _delimiter;

	public DelimiterWriter(StreamWriter streamWriter, string delimiter = ",")
	{
		_streamWriter = streamWriter;
		_delimiter = delimiter;
	}

	public void WriteData<T>(IEnumerable<T> dataCollection)
	{
		if (dataCollection != null && dataCollection.Count() > 0)
		{
			_streamWriter.WriteLine(JoinDataWithDelimiter(dataCollection));
		}
	}

	private string FormatDataToWrite(string inputString)
	{
		if (inputString.Contains("\""))
		{
			inputString = inputString.Replace("\"", "\"\"");
		}
		if (inputString.Contains(",") || inputString.Contains(Environment.NewLine) || inputString.Contains("\""))
		{
			inputString = "\"" + inputString + "\"";
		}
		return inputString;
	}

	private string JoinDataWithDelimiter<T>(IEnumerable<T> values)
	{
		if (values != null && values.Count() > 0)
		{
			return string.Join(_delimiter, values.Select((T obj) => (obj != null) ? FormatDataToWrite(obj.ToString()) : ""));
		}
		return string.Empty;
	}
}
