//
//  Events.m
//  插件中事件流转
//
//  Created by 范大德 on 2022/3/17.
//

#import <Foundation/Foundation.h>
#import "Events.h"
@interface Events()
{}
@end
@implementation Events

static NSString* PREFIX = @"com.tencent.trtc.event";
static NSMutableDictionary<NSString*,NSMutableOrderedSet<Listener*>*> *events = nil;

+ (void)fireEvent: (NSString*)event{
    [Events fireEvent: nil];
}
+ (void)fireEvent: (NSString*)event extra:(NSDictionary*)extra{
    [Events init];
    NSLog(@"TRTC - Events::fireEvent --- event:%@,extra:%@",event,extra);
    NSMutableOrderedSet* listeners = [self getEventListener:event];
    if(listeners != nil && listeners.count > 0 ){
        for (Listener* listener in listeners) {
            NSLog(@"TRTC - Events::fireEvent --- event:%@,listener:%@",event,listener);
            [listener on:extra];
        }
    }
}
+ (void)addListener: (NSString*)event listener:(Listener*)listener{
    [Events init];
    NSLog(@"TRTC - Events::addListener --- event:%@,listener:%@",event,listener);
    NSMutableOrderedSet* listeners = [self getEventListener:event];
    if(![listeners containsObject:listener]){
        [listeners addObject:listener];
    }
}
+ (void)removeListener: (NSString*)event listener:(Listener*)listener{
    [Events init];
    NSLog(@"TRTC - Events::removeListener --- event:%@,listener:%@",event,listener);
    NSMutableOrderedSet* listeners = [self getEventListener:event];
    if([listeners containsObject:listener]){
        [listeners removeObject:listener];
    }
}

+ (void)init{
    if( events == nil){
        events = [NSMutableDictionary dictionary];
    }
}
+ (NSMutableOrderedSet*) getEventListener: (NSString*)event{
    [Events init];
    NSString* key = [[NSString alloc] initWithFormat:@"%@%@", PREFIX, event ];
    NSMutableOrderedSet* listeners =[events valueForKey:key];
    if(listeners == nil){
        listeners = [[NSMutableOrderedSet alloc] init];
        [events setObject:listeners forKey:key];
    }
    return [events valueForKey:key];
}
@end
