using System;
using System.IO;

namespace XGame.Framework.FileSystem
{
    class CSharpDirectoryOperator : IDirectoryOperator
    {
        public bool Copy(string source, string destination, bool overwrite)
        {
            if (Directory.Exists(destination))
            {
                if (overwrite)
                {
                    Directory.Delete(destination, true);
                }
            }
            else
            {
                Directory.CreateDirectory(destination);
            }
            var files = Directory.GetFiles(source, "", SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
            {
                return true;
            }
            foreach (var file in files)
            {
                var destFile = file.Replace(source, destination);
                var dirPath = Path.GetDirectoryName(file);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                System.IO.File.Copy(file, destFile, overwrite);
            }
            return true;
        }

        public bool Delete(string fullDirectory, bool includeSelf = true)
        {
            Directory.Delete(fullDirectory, true);
            if (!includeSelf)
                Directory.CreateDirectory(fullDirectory);
            return true;
        }

        public IDeleteDirectoryAsync DeleteAsync(string fullDirectory, bool includeSelf = true)
        {
            DeleteDirectoryAsync deleteAsync = new DeleteDirectoryAsync(fullDirectory, includeSelf);
            deleteAsync.Start();
            return deleteAsync;
        }

        public bool Exist(string fullDirectory)
        {
            return Directory.Exists(fullDirectory);
        }

        public string GetDirectoryName(string fullDirectory)
        {
            return Path.GetDirectoryName(fullDirectory);
        }

        public string[] GetFileSystemEntries(string fullDirectory)
        {
            try
            {
                return Directory.GetFileSystemEntries(fullDirectory);
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError(e.Message);
                return null;
            }
        }

        public bool Mkdir(string fullDirectory)
        {
            Directory.CreateDirectory(fullDirectory);
            return true;
        }

        public bool Rename(string from, string to)
        {
            Directory.Move(from, to);
            return true;
        }

        public string[] GetFiles(string fullDirectory, string extension, bool recursion = true)
        {
            return Directory.GetFiles(fullDirectory, extension, recursion ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
        }
    }
}
