using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Package.Storage
{
    /// <summary>
    /// CSV数据上下文
    /// </summary>
    public class CsvDbContext
    {
        /// <summary>
        /// 加载列定义
        /// </summary>
        /// <param name="path">文件名</param>
        /// <returns>列定义</returns>
        public List<GridColumnDefintionItem> LoadColumnDefintion(string path)
        {
            if (!File.Exists(path))
                return null;

            using (StreamReader sr = new StreamReader(path, Encoding.Default))
            using (CsvReader reader = new CsvReader(sr, CultureInfo.InvariantCulture))
            {
                return reader.GetRecords<GridColumnDefintionItem>().ToList();
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="items">项列表</param>
        public void SaveColumnDefintion(string path, List<GridColumnDefintionItem> items)
        {
            using (StreamWriter writer = new StreamWriter(path, false, Encoding.Default))
            using (CsvWriter csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(items);
            }
        }
    }
}
