using System;
using System.IO;
using System.Web;
using System.Net;

namespace StubCore.Plugins.FileOperations
{
    public class FileDataOperations
    {

        private readonly string _root = "~/App_Data/";

        public bool FileExists(string path)
        {
            var isExists = false;
            var fullpath = HttpContext.Current.Server.MapPath(_root + path);

            if (File.Exists(fullpath))
            {
                isExists = true;
            }

            return isExists;
        }

        public string GetFile(string path)
        {
            string fileData = String.Empty;
            var fullpath = HttpContext.Current.Server.MapPath(_root + path);

            if (File.Exists(fullpath))
            {
                return new WebClient().DownloadString(fullpath) as string;
            }

            return fileData;
        }

        public bool SaveFile(string path, string input)
        {
            bool isSaved = true;
            var fullpath = HttpContext.Current.Server.MapPath(_root + path);

            try
            {
                File.WriteAllText(fullpath, input);
            }
            catch (Exception ex)
            {
                isSaved = false;
            }

            return isSaved;
        }

        public bool DeleteFile(string path)
        {
            bool isDeleted = true;
            var fullpath = HttpContext.Current.Server.MapPath(_root + path);

            if (File.Exists(fullpath))
            {
                try
                {
                    File.Delete(path);
                }
                catch (Exception ex)
                {
                    isDeleted = false;
                }
            }

            return isDeleted;
        }

        public bool CreateDirectory(string path)
        {
            bool isCreated = true;
            try
            {
                var fullPath = HttpContext.Current.Server.MapPath(_root + path);

                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
            }
            catch (Exception ex)
            {
                isCreated = false;
            }

            return isCreated;
        }

        public bool DirectoryExists(string path)
        {
            var fullPath = HttpContext.Current.Server.MapPath(_root + path);
            return Directory.Exists(fullPath);
        }

        public bool DeleteDirectory(string path)
        {
            bool isDeleted = true;

            try
            {
                var fullPath = HttpContext.Current.Server.MapPath(_root + path);
                Directory.Delete(fullPath, true);
            }
            catch (Exception ex)
            {
                isDeleted = false;
            }

            return isDeleted;
        }
    }
}
