//
//  CordovaEventKit.m
//  触发Cordova事件
//
//  Created by 范大德 on 2022/3/18.
//
#import <Cordova/CDVPlugin.h>

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

static CDVPlugin* cdvPlugin;

+ (void)init: (CDVPlugin*)plugin{
    cdvPlugin = plugin;
}

+ (void) fireEvent:(NSString*)event obj:(NSDictionary*) obj{
    NSString* jsonData = [self toJSON:obj];
    [CordovaEventKit fireEvent:event msg:jsonData];
}

+ (void) fireEvent:(NSString*) event msg:(NSString*) msg{
    NSLog(@"TRTC - CordovaEventKit::fireEvent --- event:%@,msg:%@",event,msg);
    
    if (cdvPlugin == nil  || event == nil || msg == nil) {
        NSLog(@"TRTC - CordovaEventKit::fireEvent --- cdvPlugin%@,event:%@,msg:%@",cdvPlugin,event,msg);
        return;
    }
    event = [event stringByReplacingOccurrencesOfString:@"\\" withString:@"_"];
    
    NSString* js = [[NSString alloc] initWithFormat:@"window.cordova.plugin.trtc.fireEvent('%@',%@)", event, msg];
    dispatch_async(dispatch_get_main_queue(), ^{
        [cdvPlugin.commandDelegate evalJs:js];
    });
}

+(NSString*) toJSON:(NSDictionary*)obj{
    NSError *error = nil;
    NSData *jsonData = nil;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [obj enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *keyString = nil;
        NSString *valueString = nil;
        if ([key isKindOfClass:[NSString class]]) {
            keyString = key;
        }else{
            keyString = [NSString stringWithFormat:@"%@",key];
        }

        if ([obj isKindOfClass:[NSString class]]) {
            valueString = obj;
        }else{
            valueString = [NSString stringWithFormat:@"%@",obj];
        }

        [dict setObject:valueString forKey:keyString];
    }];
    jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] == 0 || error != nil) {
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

@end
