using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EditorFramework;
using HybridCLR.Editor;
using HybridCLR.Editor.Settings;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace Stary.Evo.Editor
{
    public class CreatAssetWindow : OdinEditorWindow
    {
        [MenuItem("Evo/创建Domain作用域")]
        static void Init()
        {
            // Get existing open window or if none, make a new one:
            CreatAssetWindow window = (CreatAssetWindow)EditorWindow.GetWindow(typeof(CreatAssetWindow));
            window.Show();
        }

        [TitleGroup("创建Domain作用域")] public string domain;

        [TitleGroup("创建Domain作用域")]
        [Button("创建Domain", ButtonSizes.Large)]
        public async void CreatDomain()
        {
            if (GetCreatDomainAll().Count>0)
            {
                EditorUtility.DisplayDialog("错误!", "Domain仅可以创建一个，请在下方删除存在的Domain", "确定");
                return;
            }
            
            if (string.IsNullOrEmpty(domain))
            {
                EditorUtility.DisplayDialog("错误!", "请输入将要创建Domain的编号", "确定");
                return;
            }
  
            string domainPath = $"{Application.dataPath}/Domain/{domain}";
            if (Directory.Exists(domainPath+"/AddressableRes/Config/DomainConfig.asset"))
            {
                EditorUtility.DisplayDialog("错误!", $"\"{domain}\"已经存在,无法创建", "确定");
                return;
            }

            Directory.CreateDirectory(domainPath);

            //美术资源存放文件夹
            string resPath = $"{domainPath}/AddressableRes";
            Directory.CreateDirectory(resPath);
            //创建音频文件夹
            Directory.CreateDirectory(resPath + "/Audios");
            //创建Config文件夹
            Directory.CreateDirectory(resPath + "/Config");
            //创建Dll文件夹
            Directory.CreateDirectory(resPath + "/Dll");
            //创建Prefabs文件夹
            Directory.CreateDirectory(resPath + "/Prefabs");
            //创建Scenes文件夹
            Directory.CreateDirectory(resPath + "/Scenes");
            //创建SpriteAtlas文件夹
            Directory.CreateDirectory(resPath + "/SpriteAtlas");
            //创建Sprites文件夹
            Directory.CreateDirectory(resPath + "/Sprites");
            //创建Video文件夹
            Directory.CreateDirectory(resPath + "/Video");

            await File.WriteAllTextAsync($"{resPath}/这里放所有参与热更的资源.hint", "");

            //主入口预制件
            GameObject gameObj = new GameObject(domain);
            gameObj.transform.position = Vector3.zero;
            gameObj.transform.rotation = Quaternion.identity;
            gameObj.name = domain;
            Directory.CreateDirectory($"{resPath}/Prefabs");
            string rootPfbFilePath = $"Assets/Domain/{domain}/AddressableRes/Prefabs/{domain}.prefab";
            var localPath = AssetDatabase.GenerateUniqueAssetPath(rootPfbFilePath);
            PrefabUtility.SaveAsPrefabAsset(gameObj, localPath);

            //存放脚本文件夹
            string scriptsPath = $"{domainPath}/HotUpdate";
            Directory.CreateDirectory(scriptsPath);
            await File.WriteAllTextAsync($"{scriptsPath}/这里放所有参与热更的脚本文件.hint", "该文件夹中的程序集定义文件，请勿删除，非常重要。");

            //创建配置文件夹
            string confPath = $"{domainPath}/Conf";
            Directory.CreateDirectory(confPath);


            //程序集配置资源

            string hotfixDomain = $"HotUpdate_{domain}";

            string hotfixDomainAsmdef = $"{scriptsPath}/{hotfixDomain}.asmdef";
            await using (var writer = new StreamWriter(hotfixDomainAsmdef))
            {
                string body = Resources.Load<TextAsset>("AssemblyDefinitionTemplate").text;
                body = body.Replace("MODULE_IDENT", hotfixDomain);
                body = body.Replace("ROOT_NAMESPACE", hotfixDomain);
                await writer.WriteAsync(body);
            }

            // await File.WriteAllTextAsync($"{scriptsPath}/{hotfixDomain}.asmdef", body);


            // string architectureClassName = $"{domain}Architecture";
            // string architectureClassPath = $"{scriptsPath}/{architectureClassName}.txt";
            // //await File.WriteAllTextAsync($"{scriptsPath}/{architectureClassName}.cs", architectureTemplate);
            //
            // await using (var writer = new StreamWriter(architectureClassPath))
            // {
            //     
            //     string architectureTemplate = Resources.Load<TextAsset>("ArchitectureTemplate").text;
            //     architectureTemplate = architectureTemplate.Replace("XXXX", architectureClassName);
            //     await writer.WriteAsync(architectureTemplate);
            // }
            //模块化脚本生成配置
            string domainClassName = $"{domain}Domain";
            string architectureClassName = $"{domain}Architecture";

            //模块配置资源
            DomainConfig moduleConfig = CreateInstance<DomainConfig>();
            moduleConfig.domain = domain;
            moduleConfig.className = domainClassName;
            moduleConfig.mainPrefab = "Prefabs_" + gameObj.name;
            moduleConfig.@namespace = domain;
            AssetDatabase.CreateAsset(moduleConfig, $"Assets/Domain/{domain}/AddressableRes/Config/DomainConfig.asset");
            //
            //模块服务器配置资源

            HotfixMainResDomain hotfixMainResDomain = CreateInstance<HotfixMainResDomain>();
            hotfixMainResDomain.hotfixMainResDomainEntity = new HotfixMainResDomainEntity();
            hotfixMainResDomain.hotfixMainResDomainEntity.domain = domain;
            AssetDatabase.CreateAsset(hotfixMainResDomain, $"Assets/Domain/{domain}/Conf/HotfixMainResDomain.asset");

            //编辑器配置资源
            BuildAssetDataSetting buildAssetDataSetting = CreateInstance<BuildAssetDataSetting>();
            buildAssetDataSetting.packageName = domain;
            AssetDatabase.CreateAsset(buildAssetDataSetting,
                $"Assets/Domain/{domain}/Conf/BuildAssetDataSetting.asset");

            AssetDatabase.Refresh();


            string configPath = $"Assets/Domain/{domain}/HotUpdate/{hotfixDomain}.asmdef";
            AssemblyDefinitionAsset assemblyDefinitionAsset =
                AssetDatabase.LoadAssetAtPath<AssemblyDefinitionAsset>(configPath);
            // 将程序集定义添加到 HybridCLR 热更列表
            var settings = SettingsUtil.HybridCLRSettings;
            if (!settings.hotUpdateAssemblyDefinitions.Contains(assemblyDefinitionAsset))
            {
                var assemblyList = settings.hotUpdateAssemblyDefinitions.ToList();
                assemblyList.Add(assemblyDefinitionAsset);
                SettingsUtil.HybridCLRSettings.hotUpdateAssemblyDefinitions = assemblyList.ToArray();
          
            }
            

            List<AssemblyDefinitionAsset> assemblies = new List<AssemblyDefinitionAsset>();
            for (int i = 0; i < settings.hotUpdateAssemblyDefinitions.Length; i++)
            {
                if (settings.hotUpdateAssemblyDefinitions[i] != null)
                {
                    assemblies.Add(settings.hotUpdateAssemblyDefinitions[i]);
                }
            }

            HybridCLRSettings.Instance.hotUpdateAssemblyDefinitions = assemblies.ToArray();
            HybridCLRSettings.Save();
  
            AssetDatabase.SaveAssets();
 
            
            string domainClassPath = $"{scriptsPath}/{domainClassName}.cs";
            //await File.WriteAllTextAsync($"{scriptsPath}/{domainClassName}.cs", domainTemplate);
            await using (var writer = new StreamWriter(domainClassPath))
            {
                string domainTemplate = Resources.Load<TextAsset>("DomainTemplate").text;
                domainTemplate = domainTemplate.Replace("ClassNameXX", domainClassName)
                    .Replace("ReturnArchitecture", architectureClassName)
                    .Replace("ArchitectureX", architectureClassName)
                    .Replace("NamespaceX", domain);
                await writer.WriteAsync(domainTemplate);
            }
        }

        public void CreateDomainClass()
        {
        }

        public void CreateArchitectureClass()
        {
        }

        [TitleGroup("预览Domain作用域")] public List<CreatDomainEntity> domainList;

        protected override void Initialize()
        {
            base.Initialize();
            domainList = GetCreatDomainAll();
        }
        /// <summary>
        /// 获取全部作用域
        /// </summary>
        public static string[] GetCreatDomainAllName()
        {
            string domainPath = $"{Application.dataPath}/Domain";
            string[] domains;
            // 新增目录获取代码
            if (Directory.Exists(domainPath))
            {
                var dirInfo = new DirectoryInfo(domainPath);
                // 获取直接子目录（不递归）
                domains = dirInfo.GetDirectories("*", SearchOption.TopDirectoryOnly)
                    .Select(d => d.Name)
                    .ToArray();
            }
            else
            {
                domains = Array.Empty<string>();
            }

           

            return domains;
        }
        /// <summary>
        /// 获取全部作用域
        /// </summary>
        public static List<CreatDomainEntity> GetCreatDomainAll()
        {
            string domainPath = $"{Application.dataPath}/Domain";
            string[] domains;
            // 新增目录获取代码
            if (Directory.Exists(domainPath))
            {
                var dirInfo = new DirectoryInfo(domainPath);
                // 获取直接子目录（不递归）
                domains = dirInfo.GetDirectories("*", SearchOption.TopDirectoryOnly)
                    .Select(d => d.Name)
                    .ToArray();
            }
            else
            {
                domains = Array.Empty<string>();
            }

            List<CreatDomainEntity> domainList = new List<CreatDomainEntity>();
            foreach (var item in domains)
            {
                if (File.Exists($"{domainPath}/{item}/AddressableRes/Config/DomainConfig.asset"))
                {
                    CreatDomainEntity domainEntity = new CreatDomainEntity(domainList)
                    {
                        DomainName = item,
                        domainPath = $"{domainPath}/{item}"
                    };
                    domainList.Add(domainEntity);
                }
            }

            return domainList;
        }
    }
}