using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

namespace LLM.Editor.Data
{
    [InitializeOnLoad]
    public class EditorBuildHelper
    {
        static EditorBuildHelper() => Init();

        private static void Init()
        {
            var isSessionSet = SessionState.GetBool("GameSetupWindowV2_BuildBundles", false);
            if (!isSessionSet) return;
            if (EditorApplication.isCompiling) return;
            var isCurrentBundleBuildInProgress = SessionState.GetBool("GameSetupWindowV2_IsCurrentBundleBuildInProgress", false);
            if (isCurrentBundleBuildInProgress) return;
            var jsonData = SessionState.GetString("GameSetupWindowV2_SelectedPlatforms", null);
            if (string.IsNullOrEmpty(jsonData)) return;
            var platforms = JsonUtility.FromJson<List<string>>(jsonData);
            if (platforms == null || platforms.Count == 0)
            {
                ClearSession();
                return;
            }
            var platform = platforms[0];
            SessionState.SetString("GameSetupWindowV2_CurrentPlatform", platform);
            platforms.RemoveAt(0);
            SessionState.SetString("GameSetupWindowV2_BuildBundlesJson", JsonUtility.ToJson(platforms));
        }
        
        private static void ClearSession()
        {
            SessionState.EraseBool("GameSetupWindowV2_BuildBundles");
            SessionState.EraseString("GameSetupWindowV2_SelectedPlatforms");
            SessionState.EraseBool("GameSetupWindowV2_CurrentPlatform");
        }
    }
}