using System.IO;
using System.Text;

namespace XGame.Framework.FileSystem
{
    class CSharpFileOperator : IFileOperator
    {
        public bool Copy(string source, string destination, bool overwrite)
        {
            System.IO.File.Copy(source, destination, overwrite);
            return true;
        }

        public ICopyFileAsync CopyFileAsync(string source, string destination, bool overwrite)
        {
            var fileCopyAsync = new CopyFileAsync(source, destination, overwrite);
            fileCopyAsync.Start();
            return fileCopyAsync;
        }

        public bool Delete(string fullName)
        {
            System.IO.File.Delete(fullName);
            return true;
        }

        public bool Exist(string fullName)
        {
            return System.IO.File.Exists(fullName);
        }

        public string Extension(string fullName)
        {
            return Path.GetExtension(fullName);
        }

        public string GetDirectory(string fullName)
        {
            return Path.GetDirectoryName(fullName).Replace('\\', '/').Replace("//", "/");
        }

        public void Move(string source, string destination)
        {
            System.IO.File.Move(source, destination);
        }

        public byte[] ReadAllBytes(string filePath)
        {
            return System.IO.File.ReadAllBytes(filePath);
        }

        public string ReadAllText(string filePath)
        {
            byte[] bytes = System.IO.File.ReadAllBytes(filePath);
            if (bytes != null && bytes.Length > 0)
                return Encoding.UTF8.GetString(bytes);
            return string.Empty;
        }

        public IReadFileAsync ReadFileAsync(string filePath)
        {
            var fileReadAsync = new ReadFileAsync(filePath);
            fileReadAsync.Start();
            return fileReadAsync;
        }

        public void WriteAllBytes(string path, byte[] bytes)
        {
            System.IO.File.WriteAllBytes(path, bytes);
        }

        public void WriteAllText(string path, string contents)
        {
            if (string.IsNullOrEmpty(contents))
            {
                Log.Warn($"CSharpFileOperator WriteAllText failed. contents is null or empty, {path}");
                return;
            }
            var bytes = Encoding.UTF8.GetBytes(contents);
            System.IO.File.WriteAllBytes(path, bytes);
        }

        public bool Rename(string from, string to)
        {
            System.IO.File.Move(from, to);
            return true;
        }
        public string GetFileName(string fullName, bool withoutExt = true)
        {
            if (withoutExt) return Path.GetFileNameWithoutExtension(fullName);
            else return Path.GetFileName(fullName);
        }
    }
}
