using System.IO;
using UnityEditor;
using UnityEngine;

namespace ChillConnect.Editor
{
    public class BuildSome
    {
        [MenuItem("Tools/Build")]
        public static void BuildAssetBundle()
        {
            AssetBundleBuildKit.ClearAssetBundlesName();

            AssetBundleBuildKit.SetAssetBundlesName(ChillConnectConstant.croas);

            EditorApplication.isPlaying = false;

            var dir = ChillConnectConstant.tbund;

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            else
            {
                Directory.Delete(dir, true);

                Directory.CreateDirectory(dir);
            }


            var buildTarget = EditorUserBuildSettings.activeBuildTarget;

            var manifest = BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.ChunkBasedCompression,
                buildTarget);
            AssetDatabase.Refresh();

            EncryptAssetBundle();

            BuildAssetBundleFileIndex(manifest);

            Application.OpenURL(dir + "/..");
        }


        private static void EncryptAssetBundle()
        {
            var dir = ChillConnectConstant.tbund;

            var filePaths = Directory.GetFiles(dir, $"*{ChillConnectConstant.setbun}",
                SearchOption.TopDirectoryOnly);


            var encryptPath = $"{Application.dataPath}/../AssetBundlesEncrypt";

            if (!Directory.Exists(encryptPath))
            {
                Directory.CreateDirectory(encryptPath);
            }
            else
            {
                Directory.Delete(encryptPath, true);

                Directory.CreateDirectory(encryptPath);
            }

            foreach (var assetBundleFile in filePaths)
            {
                if (!assetBundleFile.EndsWith(".meta") && !assetBundleFile.Contains(".DS_Store"))
                {
                    var assetBundleName = assetBundleFile.Replace(dir, string.Empty).Replace("\\", "");
                    var encryptFilePath = Path.Combine(encryptPath, assetBundleName);
                    AESForFileKit.EncryptFile(assetBundleFile, encryptFilePath,
                        ChillConnectConstant.admsie);

                    File.Copy(encryptFilePath, Path.Combine(dir, assetBundleName), true);
                }
            }

            Directory.Delete(encryptPath, true);
        }

        private static void BuildAssetBundleFileIndex(AssetBundleManifest manifest)
        {
            var dir = ChillConnectConstant.tbund;
            var dirFile = $"{ChillConnectConstant.tbund}/../";

            var filePath = Path.Combine(dirFile, ChillConnectConstant.zyzootx);

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

            var filePaths = Directory.GetFiles(dir, $"*{ChillConnectConstant.setbun}",
                SearchOption.TopDirectoryOnly);

            using var fileStream = new FileStream(filePath, FileMode.CreateNew);

            using var streamWriter = new StreamWriter(fileStream);

            var totalAssetBundlePath = $"{dir}/{ChillConnectConstant.undles}";

            var totalAssetBundleManifestPath = $"{dir}/{ChillConnectConstant.lesest}";

            var totalMD5 = MD5Kit.GetFileMD5(totalAssetBundlePath);
            streamWriter.WriteLine(GetAssetBundleFileIndex(ChillConnectConstant.undles, totalMD5));

            var manifestMD5 = MD5Kit.GetFileMD5(totalAssetBundleManifestPath);
            streamWriter.WriteLine(GetAssetBundleFileIndex(ChillConnectConstant.lesest,
                manifestMD5));
            foreach (var assetBundleFile in filePaths)
            {
                if (!assetBundleFile.EndsWith(".meta") && !assetBundleFile.Contains(".DS_Store"))
                {
                    var fileMD5 = MD5Kit.GetFileMD5(assetBundleFile);

                    var assetBundleName = assetBundleFile.Replace(dir, string.Empty).Replace("\\", "");

                    streamWriter.WriteLine(GetAssetBundleFileIndex(assetBundleName, fileMD5));
                }
            }
        }

        private static string GetAssetBundleFileIndex(string assetBundleName, string assetBundleFileMD5)
        {
            return $"{assetBundleName}{ChillConnectConstant.fgklpk}{assetBundleFileMD5}";
        }
    }
}