MConfigEntity.cs

99 lines | 2.391 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;

using RW_Tool.Core.Abstract;
using RW_Tool.DataSource.FileOrStream;

using Tools.ConfigurationTool.Serializer;
using Tools.SingletonTool;

namespace Tools.ConfigurationTool.ConfigMultiple
{
    //Singlethon сущность конфига 
    public class MConfigEntity<T>
        : ISignlethonWithParams<MConfigParams>
        where T : class, new()
    {
        //Параметры конфига
        public MConfigParams Params { private set; get; }

        //Объект сериализации
        I_RW<T, DS_FileOrStream> Serializer;

        //Данные, хранимые в конфиге
        public Dictionary<string, T> Data { set; get; } = new Dictionary<string, T>();


        public void SetParams(MConfigParams param)
        {
            Params = param;

            Serializer = new SerializerFactory()
                .GetSerializer<T>(
                    param.ConfigDirectoryPath, 
                    param.Format
                );

            if (Directory.Exists(Params.ConfigDirectoryPath))
                ImportAll();
            ExportAll();
        }


        public void Export(string key)
        {
            Serializer.Write(
                Data[key], 
                new DS_File(Params.GetPathForFile(key))
            );
        }
        public void ExportAll()
        {
            DirectoryInfo dir = Params.ConfigDirectoryInfo;

            if (Params.RecreateDirectory)
            {
                if (dir.Exists)
                    dir.Delete(true);
            }
            dir.Refresh();
            if (!dir.Exists)
                dir.Create();

            foreach (var elem in Data)
                Export(elem.Key);
        }

        public void Import(string path)
        {
            Data.Add(
                Path.GetFileNameWithoutExtension(Path.GetFileName(path)),
                Serializer.Read(new DS_File(path))
            );
        }
        public void ImportAll()
        {
            DirectoryInfo dir = Params.ConfigDirectoryInfo;

            if (!dir.Exists)
            {
                dir.Create();
                return;
            }

            var data = dir.GetFiles();

            foreach (var elem in data)
            {
                Import(elem.FullName);
            }
        }

    }
}