﻿/*
	The MIT License

	Copyright (c) 2021 Park Hyun-Kyu

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

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

namespace IDK.GlobalMessage {

    [System.Serializable]
    public class MessageItem
    {
        [HideInInspector]
        public string messageID="";

        [SerializeField]
        public string name;
        
        [SerializeField]
        public string  method;

        [SerializeField]
        public string defaultParameter = string.Empty;
        private string lastParameter = string.Empty;

        [SerializeField]
        public MonoBehaviour target;

        [SerializeField]
        [HideInInspector]
        public MethodInfo methodInfo;

        object [] parameters = null;

        public MessageItem (
            string _name, 
            string _mehtod, 
            MonoBehaviour _target, 
            string _parameters = ""
        )
        {
            method = _mehtod;
            target = _target;
            name = _name;
            defaultParameter = _parameters;
        }
        public void Update()
        {
            ParsingMethod();
            ParsingParameter();
        }

        public object Run(object [] _params)
        {
            if(_params == null)
            {
                ParsingParameter();
            }

            return (object) methodInfo.Invoke(
                target, 
                ( _params == null ? parameters : _params )
            );
        }

        public object Run()
        {
            ParsingParameter();
            return (object) methodInfo.Invoke(target, parameters);
        }

        public bool Equals( MessageItem _item)
        {
            return (
							(method == _item.method) && 
							(name == _item.name) && 
							(target == _item.target)
						);
        }

        void ParsingMethod()
        {
            if(methodInfo != null || method.Equals(string.Empty))
            {
                return;
            }
            methodInfo = target.GetType().GetMethod(method);
            messageID = String.Format(
                "{0}%{1}", 
                target.gameObject.name, 
                target.GetInstanceID()
            );
        }

        void ParsingParameter()
        {
            if(lastParameter == defaultParameter || string.IsNullOrEmpty(defaultParameter))
            {
                return;
            }
            lastParameter = defaultParameter;

            // 기본파라미터의 수와 메소드의 파라미터 수가 다를 때 
            // IndexOutOfRangeException가 발생합니다.
            string [] parameterStrings = defaultParameter.Split('|');

            if(parameterStrings.Length <= 0)
            {
                return;
            }
            ParameterInfo[] paramArray = methodInfo.GetParameters();
            if(paramArray.Length > 0)
            {
                parameters = new object [paramArray.Length];
                foreach(ParameterInfo info in paramArray)
                {
                    parameters[info.Position] = Convert.ChangeType(
                        parameterStrings[info.Position], 
                        info.ParameterType
                    );
                }
            }
        }
    }

    public class GlobalMessage : MonoBehaviour
    {
        static public Hashtable Send(string key, object [] message = null)
        {
            int count = GlobalMessageManager.lst.Count;
            Hashtable returns = new Hashtable();
            List<MessageItem> msgSets = GlobalMessageManager.lst.FindAll( 
                x => x.name.Equals(key) 
            );
            int i=0;
            while(msgSets.Count > i)
            {
                MessageItem item = msgSets[i];

                // 액티브 오브젝트만 호출
                // if(!item.target.gameObject.activeSelf)
                // {
                //     continue;
                // }

                object returnValue = null;
                try{
                    returnValue = item.Run(message);
                }
                catch(Exception e)
                {
                    string errMsg = item.messageID + " : " + e.Message;
                    UnityEngine.Debug.LogAssertion(errMsg,item.target);
                    returnValue = null;
                    GlobalMessageManager.lst.Remove(item);
                }
                if(returnValue != null)
                {
                  returns.Add (item.messageID, returnValue );
                }
                i++;
            }
            return returns;
        }

        [HideInInspector]
        public bool isRegistered = false;

        public List<MessageItem> messages = new List<MessageItem>();

        void Start()
        {
            if(!isRegistered)
            {
                isRegistered = true;
                GlobalMessageManager.Add(this);
            }     
        }

        void OnDestroy ()
        {
            GlobalMessageManager.Remove(this);
        }
    }

}