
using System.IO;
using UnityEngine;

namespace XenseAR.Localization
{
    public class FileUtility
    {
        public static string ReadFileData(string directory, string path)
        {
            string fileText = "";

            string CachePath = directory;
            if (string.IsNullOrEmpty(path))
            {
                throw new System.Exception("The file path could not be empty");
            }

            string[] folderNames = path.Split("/");
            for (int i = 0; i < folderNames.Length - 1; i++)
            {
                CachePath = Path.Combine(CachePath, folderNames[i]);
                if (!Directory.Exists(CachePath))
                {
                    Directory.CreateDirectory(CachePath);
                }
            }

            CachePath = Path.Combine(CachePath, folderNames[folderNames.Length - 1]);

            if (!File.Exists(CachePath))
            {
                throw new System.Exception("The path does not exist");
            }

            fileText = File.ReadAllText(CachePath);

            return fileText;
        }

        public static void WriteFileData(string directory, string path, string data) {
            string CachePath = directory;
            if (string.IsNullOrEmpty(path)) {
                throw new System.Exception("The file path could not be empty");
            }

            string[] folderNames = path.Split("/");
            for (int i = 0; i < folderNames.Length - 1; i++)
            {
                CachePath = Path.Combine(CachePath, folderNames[i]);
                if (!Directory.Exists(CachePath))
                {
                    Directory.CreateDirectory(CachePath);
                }
            }

            CachePath = Path.Combine(CachePath, folderNames[folderNames.Length - 1]);

            if (File.Exists(CachePath)) { 
                File.Delete(CachePath);
            }

            File.WriteAllText(CachePath, data);
        }

        public static string GetLink(string root, string relativePath)
        {
            string absoluteUrl = root.Replace(root.Substring(root.LastIndexOf("/")), relativePath);
            return absoluteUrl;
        }
    }
}

