using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace IOB_UT_NEXT
{
    public class DataExport
    {

        /// <summary>
        /// Effettua salvataggio in file di un generico oggetto in formato CSV
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reportData">Lista oggetti da esportare</param>
        /// <param name="path">Percorso file di output</param>
        /// <param name="writeHeader">Indica se scrivere header ad inizio CSV</param>
        /// <param name="separator">Separatore da impiegare (default ";")</param>
        /// <returns></returns>
        public static bool SaveToCsv<T>(List<T> reportData, string path, bool writeHeader, char separator = ';')
        {
            bool answ = false;
            var lines = new List<string>();
            try
            {
                IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();
                var elencoValori = props.ToList();
                var header = string.Join($"{separator}", props.ToList().Select(x => !string.IsNullOrEmpty(x.Description) ? x.Description : x.Name));
                var fieldList = string.Join($"{separator}", props.ToList().Select(x => x.Name));
                if (writeHeader)
                {
                    lines.Add(header);
                }
                var valueLines = reportData.Select(row => string.Join($"{separator}", fieldList.Split(separator).Select(a => row.GetType().GetProperty(a).GetValue(row, null))));
                lines.AddRange(valueLines);
                File.WriteAllLines(path, lines.ToArray());
                answ = true;
            }
            catch
            { }
            return answ;
        }

        /// <summary>
        /// Effettua salvataggio in file di un generico oggetto in formato Fixed width
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reportData">Lista oggetti da esportare</param>
        /// <param name="path">Percorso file di output</param>
        /// <param name="widthList">Vettore delle larghezze richieste</param>
        /// <returns></returns>
        public static bool SaveFixedWidth<T>(List<T> reportData, string path, Dictionary<string, int> widthList, Dictionary<string, char> fieldLPad, Dictionary<string, int> numDecReq)
        {
            bool answ = false;
            var lines = new List<string>();
            try
            {
                IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();
                var elencoValori = props.ToList();
                foreach (var dataRow in reportData)
                {
                    string currRow = "";
                    // processo 1:1 x width...
                    foreach (var item in widthList)
                    {
                        string currValue = dataRow.GetType().GetProperty(item.Key).GetValue(dataRow, null).ToString();
                        // se ha un num decimali specifico richiesto esegue...
                        if (numDecReq.ContainsKey(item.Key))
                        {
                            string nDec = $"N{numDecReq[item.Key]}";
                            decimal rawVal = 0;
                            decimal.TryParse(currValue, out rawVal);
                            currValue = rawVal.ToString(nDec);
                        }
                        if (currValue.Length > item.Value)
                        {
                            currValue = currValue.Substring(0, item.Value);
                        }
                        // se ha un LPad richiesto esegue...
                        if (fieldLPad.ContainsKey(item.Key))
                        {
                            currValue = currValue.PadLeft(item.Value, fieldLPad[item.Key]);
                        }
                        currRow += string.Format($"{{0,-{item.Value}}}", currValue);
                    }
                    lines.Add(currRow);
                }
                File.WriteAllLines(path, lines.ToArray());
                answ = true;
            }
            catch
            { }
            return answ;
        }
    }
}
