using System.IO;
using SGModule.Common.Helper;
using UnityEditor;
using UnityEngine;

namespace SwhiteGames.Editor {
    public class GameConfigCreator : EditorWindow {
        public string packName = "";
        public bool enabledLog = true;
        public bool hardwareAcceleration = true;

        private string _configFileName = "GameConfig";

        private void OnGUI() {
            GUILayout.Label("GameConfig Settings", EditorStyles.boldLabel);
            _configFileName = EditorGUILayout.TextField("Character Name", _configFileName);

            packName = EditorGUILayout.TextField(string.IsNullOrEmpty(packName) ? "请输入包名..." : "包名",
                packName);

            enabledLog = EditorGUILayout.Toggle("开启日志", enabledLog);

#if UNITY_ANDROID
            hardwareAcceleration = EditorGUILayout.Toggle("硬件加速", hardwareAcceleration);
#endif
            if (GUILayout.Button("Create")) {
                if (string.IsNullOrEmpty(packName)) {
                    EditorUtility.DisplayDialog("请填写正确配置",
                        $"packName {!string.IsNullOrEmpty(packName)}",
                        "确定");
                    return;
                }

                CreateGameConfig();
                Close();
            }
        }

        [MenuItem("SwhiteGames/Create GameConfig")]
        public static void ShowWindow() {
            GetWindow<GameConfigCreator>("Create GameConfig");
        }

        private void CreateGameConfig() {
            // 确保 Resources 文件夹存在
            var resourcesPath = Path.Combine("Assets", "Resources");
            if (!Directory.Exists(resourcesPath)) {
                Directory.CreateDirectory(resourcesPath);
                AssetDatabase.Refresh(); // 刷新资源数据库

                Log.Common.Info("Resources 文件夹已创建。");
            }

            // 检查同名文件
            var assetPath = Path.Combine(resourcesPath, _configFileName + ".asset");
            if (File.Exists(assetPath)) {
                // 如果同名文件已存在，弹出提示并结束逻辑
                EditorUtility.DisplayDialog("文件已存在", $"配置文件 '{_configFileName}' 已存在于 Resources 文件夹中。", "确定");
                return;
            }

            // 创建并设置 config 实例
            var gameConfig = CreateInstance<GameConfig>();
            gameConfig.packageName = packName;
            gameConfig.enabledLog = enabledLog;
            gameConfig.hardwareAcceleration = hardwareAcceleration;

            // 将 ScriptableObject 实例保存到 Resources 文件夹中
            AssetDatabase.CreateAsset(gameConfig, assetPath);
            AssetDatabase.SaveAssets();

            Log.Common.Info("GameConfig 配置文件已成功创建在 " + assetPath);
        }
    }
}
