using System.IO;
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using UnityEngine.Networking;

namespace ChillConnect
{
    public class DownloadKit
    {
        private static void SaveTextFile(string content, string filePath, string fileName)
        {
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            File.WriteAllText($"{filePath}{fileName}.txt", content);
        }

        public static void SaveFile(string content, string filePath, string fileName)
        {
            SaveTextFile(content, filePath, fileName);
        }

        private static void SaveTextFile(byte[] content, string filePath, string fileName)
        {
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            File.WriteAllBytes($"{filePath}{fileName}.txt", content);
        }

        public static IEnumerator GetTextFromUrl(string url, string fileName, UnityAction<string> action = null,
            string savePath = null, bool isSave = true)
        {
            var unityWebRequest = UnityWebRequest.Get(url);
            yield return unityWebRequest.SendWebRequest();
            if (unityWebRequest.result is UnityWebRequest.Result.ConnectionError
                or UnityWebRequest.Result.ProtocolError)
            {
                yield return null;
                action?.Invoke(default);
                yield break;
            }

            var content = unityWebRequest.downloadHandler.text;
            if (isSave)
            {
                savePath ??= ChillConnectFileKit.GetFilePath();
                SaveTextFile(content, savePath, fileName);
            }

            yield return null;
            action?.Invoke(content);
        }

        public static IEnumerator GetTextFromUrl1(string url, string fileName, UnityAction<string> action = null,
                    string savePath = null, bool isSave = true)
        {
            var www = new WWW(url);

            while (!www.isDone)
            {
            }

            if (isSave)
            {
                savePath ??= ChillConnectFileKit.GetFilePath();
                SaveTextFile(www.bytes, savePath, fileName);
            }

            yield return null;
            action?.Invoke(System.Text.Encoding.UTF8.GetString(www.bytes));
        }

        public static void GetTextFromUrl2(string url, string fileName, UnityAction<string> action = null,
            string savePath = null, bool isSave = true)
        {
            var www = new WWW(url);

            while (!www.isDone)
            {
            }

            if (isSave)
            {
                savePath ??= ChillConnectFileKit.GetFilePath();
                SaveTextFile(www.bytes, savePath, fileName);
            }

            // yield return null;
            action?.Invoke(System.Text.Encoding.UTF8.GetString(www.bytes));
        }

        public static IEnumerator GetFileFromUrl(string url, string fileName, UnityAction<bool> action)
        {
            var unityWebRequest = UnityWebRequest.Get(url);
            yield return unityWebRequest.SendWebRequest();
            if (unityWebRequest.result is
                UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError)
            {
                action?.Invoke(false);
                yield break;
            }

            var results = unityWebRequest.downloadHandler.data;
            var savePath = ChillConnectFileKit.GetFilePath();

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = $"{savePath}{fileName}";
            var fileInfo = new FileInfo(filePath);
            var fs = fileInfo.Create();
            fs.Write(results, 0, results.Length);
            fs.Flush();
            fs.Close();
            fs.Dispose();
            yield return YieldConst.WaitForEndOfFrame;
            action?.Invoke(true);
        }

        public static string DownloadResourceSync(string url, string savePath, string fileName, bool isSave = true)
        {
            using (var unityWebRequest = UnityWebRequest.Get(url))
            {
                unityWebRequest.SendWebRequest();

                while (!unityWebRequest.isDone)
                {
                    // 等待下载完成
                }

                if (unityWebRequest.result == UnityWebRequest.Result.ConnectionError ||
                    unityWebRequest.result == UnityWebRequest.Result.ProtocolError)
                {
                    Debug.LogError($"Error downloading resource: {unityWebRequest.error}");
                    return "";
                }

                var content = unityWebRequest.downloadHandler.text;
                if (isSave)
                {
                    savePath ??= ChillConnectFileKit.GetFilePath();
                    SaveTextFile(content, savePath, fileName);
                }

                return content;
            }
        }
    }
}