using XGame.Framework.Asyncs;
using System.IO;
using System.Threading.Tasks;

namespace XGame.Framework.FileSystem
{
    public class DeleteDirectoryAsync : Async, IDeleteDirectoryAsync
    {
        readonly string _fullDirectory;
        readonly bool _includeSelf;
        public DeleteDirectoryAsync(string fullDirectory, bool includeSelf)
        {
            _fullDirectory = fullDirectory;
            _includeSelf = includeSelf;
        }

        public void Start()
        {
            try
            {
                if (!Directory.Exists(_fullDirectory)) { Completed(); return; }
                Task.Factory.StartNew(ThreadRemoveDirectories);
            }
            catch (System.Exception e)
            {
                Exception = e;
                Completed();
            }

        }

        private void OnThreadCompleted(object context)
        {
            if (null != context) Exception = context as System.Exception;
            Completed();
        }


        private void ThreadRemoveDirectories()
        {
            try
            {
                if (RemoveDirectories(_fullDirectory, _includeSelf))
                    ThreadScheduler.ThreadSchedulers.RunOnMainThread(OnThreadCompleted, null);
                else
                    ThreadScheduler.ThreadSchedulers.RunOnMainThread(OnThreadCompleted, new System.Exception("CPlusPlusDirectoryDeleteAsync::ThreadRemoveDirectories fail.."));
            }
            catch (System.Exception e)
            {
                ThreadScheduler.ThreadSchedulers.RunOnMainThread(OnThreadCompleted, e);
            }
        }


        private bool RemoveDirectories(string fullDirectory, bool includeSelf)
        {
            if (includeSelf)
                Directory.Delete(fullDirectory);
            else
            {
                Directory.Delete(fullDirectory);
                Directory.CreateDirectory(fullDirectory);
            }
            return true;
        }
    }
}
