﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace MPStudio
{
    public class AutoRunActionAttribute : Attribute
    {
        public string Description { get; }
    }
    
    [DisallowMultipleComponent]
    [DefaultExecutionOrder(-1)]
    public class GMManager : MonoBehaviour
    {
        string cmdStr = "";
        string resultStr = "";
        
        public virtual void Awake()
        {
            
        }

        protected virtual void Start()
        {
            AutoRunFunc();
        }

        [AutoRunAction]
        private static void Func1()
        {
            print("hello Func1");
        }

        private void AutoRunFunc()
        {
            var asm = Assembly.GetExecutingAssembly();
            var types = asm.GetTypes();

            foreach (var t in types)
            {
                var _methods = t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);

                foreach (var m in _methods)
                {
                    var _attrs = m.GetCustomAttributes(typeof(AutoRunActionAttribute), false);
                    if (_attrs.Length > 0)
                    {
                        m.Invoke(null, new object[] { });
                        break;
                    }
                }
            }
        }

        string RunFunc(string ipt)
        {
            string[] argArr = ipt.Split(" "[0]);
            string funcName = argArr[0];
            if (funcName == "add")
            {
                return "add";
            }
            else if (funcName == "reduce")
            {
                return "reduce";
            }

            return "运行成功";
        }

        void OnGUI()
        {
            GUI.color = Color.yellow;
            cmdStr = GUI.TextField(new Rect(10, 30, 300, 30), cmdStr, 10);
            if (GUI.Button(new Rect(10, 60, 300, 30), "运行"))
            {
                resultStr = RunFunc(cmdStr);
            }

            GUI.Label(new Rect(10, 90, 300, 30), resultStr);
        }

    }
}