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

using System.IO;
using System.Text;

using Learn_CSS.Model.Entities;

using Learn_CSS.Model.DAL.Serialization;

namespace Learn_CSS.Model.DAL
{

    public class CSSTaskStorage
    {
        private readonly DirectoryInfo TaskDirectory;
        private readonly TaskSerializerService TaskSerializerService;

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


        public CSSTaskStorage(
            string taskDirectory,
            TaskSerializerService taskSerializerService
            )
        {
            TaskSerializerService = taskSerializerService;

            TaskDirectory = new DirectoryInfo(taskDirectory);
            if (!TaskDirectory.Exists)
            {
                throw new Exception("Папка с заданиями не найдена");
            }
        }


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

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

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


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

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

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

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

    }
}

