/*
	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.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace IDK.GlobalMessage {
	public class GlobalMessageManager : MonoBehaviour
	{
		public static GlobalMessageManager instance;
		public static List<MessageItem> lst = null ;
		public readonly static object lockList = new object();
		Type msgListType = typeof( List<MessageItem> );

		public static void Add(MonoBehaviour _mono)
		{
			instance.UpdateMessage(_mono, false);
		}
		

		public static void Remove(MonoBehaviour _mono)
		{
			instance.UpdateMessage(_mono , true);
		}


		public List<MessageItem> list = null ;

		void Awake()
		{
			instance = this;

			if(lst != null)
			{
				lst.Clear();
			}
			lst = new List<MessageItem>();
			list = lst;
			SearchAll();

		}

		void SearchAll()
		{

			var foundMono = FindObjectsOfType<MonoBehaviour>(true);
			foreach(MonoBehaviour mono in foundMono)
			{
				UpdateMessage(mono , false);
				GlobalMessage gmObj = mono.GetComponent<GlobalMessage>();
				if(gmObj != null)
				{
					gmObj.isRegistered = true;
					// foreach(MessageItem item in gmObj.messages)
					// {
					// 	lst.Add(item);
					// }
					
				}
			}
		}

		void UpdateMessage( MonoBehaviour mono, bool remove = false )
		{
			MethodInfo[] methods = mono.GetType().GetMethods(
				BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly
			);
			foreach (MethodInfo mthd in methods)
			{
				MessageAttribute msgAttr;
				msgAttr = mthd.GetCustomAttribute<MessageAttribute>();
				if (msgAttr != null)
				{
					MessageItem findItem = lst.Find( 
						p => p.target == mono && p.name == msgAttr.name
					);
					if( findItem != null)
					{
						if(remove)
						{
							lst.Remove(findItem);
						}
					}
					else
					{
						lock (lockList)
						{
							MessageItem item = new MessageItem( 
								msgAttr.name, 
								mthd.Name, 
								mono, 
								msgAttr.parameters
							);
							item.Update();
							lst.Add(item);
						}
					}	
				}			
			}

			MemberInfo[] mems = mono.GetType().GetMembers(
				BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly
			);

			foreach (MemberInfo mem in mems)
			{
				if(mem.MemberType == MemberTypes.Field)
				{
					var msgList = ((FieldInfo)mem).GetValue(mono);
					if(   msgList.GetType().Equals( msgListType )   ){
						foreach(MessageItem item in (List<MessageItem>)msgList)
						{
							MessageItem findItem = lst.Find( p => p.Equals(item) );
							if( findItem != null )
							{
								if(remove)
								{
									lst.Remove(findItem);
								}
							}
							else
							{
								if(item.target == null)
								{
									if(mono.GetType().Equals(typeof(GlobalMessage)))
									{
										continue;
									}
									item.target = mono;
								}
								item.Update();
								lst.Add(item);
							}						
						}
					}
				}
			}
		}
	}   
}