using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using System.Text;

using Tools.SingletonTool.Base;

using Learn_CSS.APP.Web.Models.Services;

namespace Learn_CSS.APP.Web.Models.Entities
{
    public class StorageParams
    {
        public string Directory { set; get; }

        public TaskSerializerService TaskSerializerService { set; get; }
    }

    public class Storage : ISignlethonWithParams<StorageParams>
    {
        StorageParams param;


        public List<TaskEntity> data { private set; get; }
            = new List<TaskEntity>();

        public void SetParams(StorageParams param)
        {
            this.param = param;
        }


        /// <summary>
        /// Прочитать задания
        /// </summary>
        public void Load() 
        {           
            DirectoryInfo dir = new DirectoryInfo(param.Directory);

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

            data.Clear();

            var files = dir.GetFiles();
            foreach (var elem in files) 
            {
                data.Add(param.TaskSerializerService.Load(elem.FullName));
            }
        }


        /// <summary>
        /// Сохранение в файловую систему с предварительной отчисткой
        /// </summary>
        public void Save() 
        {
            DirectoryInfo dir = new DirectoryInfo(param.Directory);

            if (dir.Exists)
            {
                dir.Delete(true);
            }

            System.Threading.Thread.Sleep(250);
            dir.Create();

            for (int i = 0; i< data.Count; i++)
            {
                var elem = data[i];
                param.TaskSerializerService.Save(elem, Path.Combine(dir.FullName, elem.FileName));
            }
        }
        
    }
}