using System;
using System.Collections.Generic;
using RPGCore.Core;
using RPGCore.Core.Objects;
using UnityEngine;
namespace RPGCore.ObjectModules.EventObjectModule
{
[Serializable]
[ObjectModule(
name: "[Core] Data",
description: "[Built-in module] Manages all implementations of BaseEvent and BasePreventableEvent. " +
"Allows for registering and invoking events by its type.",
required: true
)]
public class EventModule : ObjectModule
{
// TODO: 1. tutaj dodać serializowane eventy w postaci SerializableDictionary
// TODO: w Awake() zrobić bridge to uruchamiania serializowanych eventów jak uruchamia się ten runtimeowy
// TODO: 2. dodatkowo mozna zmienić preventableEvents na dwa osobne słowniki before i after
internal readonly Dictionary events = new();
internal readonly Dictionary preventableEvents = new();
/***** INVOKE *****/
public void Invoke(T baseEvent) where T : BaseEvent
{
events.TryAdd(typeof(T), null);
(events[typeof(T)] as Action)?.Invoke(baseEvent);
}
public void Register(Action action) where T : BaseEvent
{
events.TryAdd(typeof(T), null);
events[typeof(T)] = (Action)events[typeof(T)] + action;
}
public void Unregister(Action action) where T : BaseEvent
{
events.TryAdd(typeof(T), null);
events[typeof(T)] = (Action)events[typeof(T)] - action;
}
/***** INVOKE BEFORE *****/
public void InvokeBefore(T basePreventableEvent) where T : BasePreventableEvent
{
preventableEvents.TryAdd(typeof(T), new Delegate[2]);
(preventableEvents[typeof(T)][0] as Action)?.Invoke(basePreventableEvent);
}
public void RegisterBefore(Action action) where T : BasePreventableEvent
{
preventableEvents.TryAdd(typeof(T), new Delegate[2]);
preventableEvents[typeof(T)][0] = (Action)preventableEvents[typeof(T)][0] + action;
}
public void UnregisterBefore(Action action) where T : BasePreventableEvent
{
preventableEvents.TryAdd(typeof(T), new Delegate[2]);
preventableEvents[typeof(T)][0] = (Action)preventableEvents[typeof(T)][0] - action;
}
/***** INVOKE AFTER *****/
public void InvokeAfter(T basePreventableEvent) where T : BasePreventableEvent
{
if (basePreventableEvent.isPrevented)
{
Debug.LogWarning("Event is prevented and can't be invoked!");
return;
}
preventableEvents.TryAdd(typeof(T), new Delegate[2]);
(preventableEvents[typeof(T)][1] as Action)?.Invoke(basePreventableEvent);
}
public void RegisterAfter(Action action) where T : BasePreventableEvent
{
preventableEvents.TryAdd(typeof(T), new Delegate[2]);
preventableEvents[typeof(T)][1] = (Action)preventableEvents[typeof(T)][1] + action;
}
public void UnregisterAfter(Action action) where T : BasePreventableEvent
{
preventableEvents.TryAdd(typeof(T), new Delegate[2]);
preventableEvents[typeof(T)][1] = (Action)preventableEvents[typeof(T)][1] - action;
}
}
}