﻿using System.Collections.Generic;
using JLGames.RocketDriver.Actions.Languages.Lua;
using JLGames.RocketDriver.Actions.Utils;
using JLGames.RocketDriver.CSharp.Languages.Lua;
using UnityEngine;

namespace JLGames.RocketDriver.Actions.Languages.Lua
{
    public class LuaBehaviour : MonoBehaviour
    {
        [SerializeField] protected bool m_AutoReplace;
        [SerializeField] protected string m_AotName;
        [SerializeField] protected bool m_AotRemove;
        [SerializeField] protected string m_LuaCode;

        protected LuaTable m_Environment;
        protected HashSet<string> m_EventSet;

        public void ReplaceUnityBehaviour(string aotName, string luaCode)
        {
            m_AutoReplace = true;
            m_AotName = aotName;
            m_LuaCode = luaCode;
            if (!string.IsNullOrEmpty(aotName))
            {
                var mono = transform.GetComponent(aotName) as MonoBehaviour;
                if (null != mono)
                {
                    if (m_AotRemove)
                        Destroy(mono);
                    else
                        mono.enabled = false;
                }
            }

            if (!string.IsNullOrEmpty(luaCode))
            {
                m_Environment = new LuaTable(Lua.Environment);
                AfterEnv();
                var fixLuaCode = $"{luaCode}\n";
                m_EventSet = UnityEventFunctions.StatEventSet(fixLuaCode);
                LuaInterpreter.Interpreter(fixLuaCode, m_Environment);
            }
        }

        protected virtual void AfterEnv()
        {
            m_Environment.RegisterMethodFunction("transform",this,LuaValueUtils.GetMethodInfo(() => Trans()));
        }

        public Transform Trans()
        {
            return transform;
        }

        protected virtual void Awake()
        {
            if (!m_AutoReplace) return;
            ReplaceUnityBehaviour(m_AotName, m_LuaCode);
        }

        protected virtual void OnDestroy()
        {
            UnityEventFunctions.TryRunLuaFunction(m_Environment, m_EventSet, "OnDestroy");
            m_Environment = null;
            m_EventSet = null;
        }

        protected virtual void Start()
        {
            UnityEventFunctions.TryRunLuaFunction(m_Environment, m_EventSet, "Start");
        }

        protected virtual void OnEnable()
        {
            UnityEventFunctions.TryRunLuaFunction(m_Environment, m_EventSet, "OnEnable");
        }

        protected virtual void OnDisable()
        {
            UnityEventFunctions.TryRunLuaFunction(m_Environment, m_EventSet, "OnDisable");
        }
    }
}