/****************************************************
    文件：PreferenceExecutor.cs
    作者：陶长春
    邮箱：376248129@qq.com
    日期：2025年2月11日 6:57:08
    UnityVersion: 2021.3.13f1
    功能：偏好设置执行器
*****************************************************/
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
using System;
using UnityEngine.SceneManagement;

namespace TFramework
{
    [InitializeOnLoad]
    public class PreferenceExecutor
    {
        const string DATAPATH = "Assets/TFramework/Editor/Data/PreferenceData.asset";
        static PreferenceData preferenceData;

        static double _lastTime;

        static PreferenceExecutor()
        {
            preferenceData = AssetDatabase.LoadAssetAtPath<PreferenceData>(DATAPATH);

            EditorApplication.update += Update;
            _lastTime = EditorApplication.timeSinceStartup;
        }

        private static void Update()
        {
            if(preferenceData&&preferenceData.m_isAutoSave && !EditorApplication.isPlaying)
            {
                if(EditorApplication.timeSinceStartup-_lastTime>=preferenceData.m_autoSaveTime)
                {
                    EditorApplication.ExecuteMenuItem("File/Save");
                    _lastTime = EditorApplication.timeSinceStartup;
                }
            }
        }

        [RuntimeInitializeOnLoadMethod]
        private static void OnEditorRunTime()
        {
            if (preferenceData == null) return;
            if (preferenceData.m_isAlwaysFormAssignScene)
                if (!string.IsNullOrEmpty(preferenceData.m_assignScene) && SceneManager.GetActiveScene().path != preferenceData.m_assignScene)
                {
                    SceneManager.LoadScene(preferenceData.m_assignScene);
                }
        }
    }
}