using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;

using Model.Entities.Base;
using Model.Entities.Files.FS_Entities;
using Model.UnitsOfWork;

namespace Model.Entities.Files.Repo
{
    public class Repo_SDirectory : Base_FS_Repository<SDirectory>
    {
        public Repo_SDirectory(UOW uOW) : base(uOW, Enum_BaseDirectoryEntity.Directory) { }

        protected override void Validation_Create(SDirectory elem)
        {
            if (string.IsNullOrEmpty(elem.Name))
                throw Repo_Exception<SDirectory>.Factory(this, elem, Repo_Exceptions.Name_is_null_or_empty);

            if (elem.Parent == null)
                throw Repo_Exception<SDirectory>.Factory(this, elem, Repo_Exceptions.Parent_is_null);

            if (elem.Parent.ID == elem.ID)
                throw new Exception();

            if (elem.Parent.ContainsName(elem))
                throw Repo_Exception<SDirectory>.Factory(this, elem, Repo_Exceptions.Name_already_exists_in_parents);

            try
            {
                Directory.CreateDirectory(elem.PhysicalPath);
            }
            catch (Exception ex)
            {
                throw new Repo_Exception<SDirectory>(this, elem, "", ex);
            }
        }

        protected override void Validation_Update(SDirectory old, SDirectory elem)
        {
            if (elem.Parent == null)
                throw Repo_Exception<SDirectory>.Factory(this, elem, Repo_Exceptions.Parent_is_null);

            if (elem.Parent.ID == elem.ID)
                throw new Exception();

            if (old.Parent != elem.Parent)
            {
                if (elem.Parent.ContainsName(elem))
                        throw Repo_Exception<SDirectory>.Factory(this, elem, Repo_Exceptions.Name_already_exists_in_parents);

                try
                {
                    Directory.Move(old.PhysicalPath, elem.PhysicalPath);
                }
                catch (Exception ex)
                {
                    throw new Repo_Exception<SDirectory>(this, elem, "", ex);
                }
            }
        }

        protected override void Validation_Delete(SDirectory elem)
        {
            if (elem.Items.Count() != 0)
                throw Repo_Exception<SDirectory>.Factory(this, elem, Repo_Exceptions.Elem_items_not_empty);

            try
            {
                Directory.Delete(elem.PhysicalPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
