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

namespace Quadarax.Foundation.Core.Data
{
    public static class CsvHelper
    {
        /// <summary>
        /// Read CSV file and creates <see cref="DataTable"/> with filled content.
        /// <remarks>
        /// This method expects first header row.
        /// </remarks>
        /// </summary>
        /// <param name="csvFile">(*.csv) full file name.</param>
        /// <param name="delimiter">Delimiter character</param>
        /// <returns>New created DataTable with content.</returns>
        public static DataTable CsvToDataTable(string csvFile, string delimiter)
        {
            var dt = new DataTable();
            using (var sr = new StreamReader(csvFile))
            {

                var headers = sr?.ReadLine()?.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
                if (headers == null) return dt;
                foreach (var header in headers)
                {
                    dt.Columns.Add(header);
                }

                while (sr is { EndOfStream: false })
                {
                    var rows = sr?.ReadLine()?.Split(new[] { delimiter }, StringSplitOptions.None);
                    if (rows == null) continue;

                    var dr = dt.NewRow();
                    for (var i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }

                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
    }
}
