//
//  ExtSdkWrapper.m
//
//
//  Created by 杜洁鹏 on 2019/10/8.
//

#import "ExtSdkWrapper.h"
#import "ExtSdkDispatch.h"
#import "ExtSdkToJson.h"

#define easemob_dispatch_main_async_safe(block)                                \
    if ([NSThread isMainThread]) {                                             \
        block();                                                               \
    } else {                                                                   \
        dispatch_async(dispatch_get_main_queue(), block);                      \
    }

static NSString *const TAG = @"ExtSdkWrapper";
@implementation ExtSdkWrapper

- (void)onResult:(nonnull id<ExtSdkCallbackObjc>)result
    withMethodType:(nonnull NSString *)methodType
         withError:(nullable AgoraChatError *)error
        withParams:(nullable NSObject *)params {
    NSLog(@"%@: onResult: %@, %@, %@", TAG, methodType,
          error ? [error toJsonObject] : @"", params ? params : @"");
    if (nil == error) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        if (params) {
            data[methodType] = params;
        }
        [result onSuccess:data];
    } else {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        data[@"error"] = [error toJsonObject];
        [result onFail:error.code withExtension:data];
    }
}

- (void)onReceive:(NSString *)methodType
       withParams:(nullable NSObject *)params {
    [[ExtSdkDispatch getInstance] onReceive:methodType withParams:params];
}

- (BOOL)checkMessageParams:(nonnull id<ExtSdkCallbackObjc>)result
            withMethodType:(nonnull NSString *)methodType
               withMessage:(nullable AgoraChatMessage *)message {
    if (message == nil) {
        [self onResult:result
            withMethodType:methodType
                 withError:[AgoraChatError errorWithDescription:
                                        @"The message does not exist."
                                                    code:1]
                withParams:nil];
        return YES;
    }
    return NO;
}

- (BOOL)getMessageParams:(nonnull id<ExtSdkCallbackObjc>)result
          withMethodType:(nonnull NSString *)methodType
             withMessage:(nullable AgoraChatMessage *)message {
    if (message == nil) {
        [self onResult:result
            withMethodType:methodType
                 withError:nil
                withParams:nil];
        return YES;
    }
    return NO;
}

- (void)mergeMessageBody:(AgoraChatMessageBody *)msgBody
       withDBMessageBody:(AgoraChatMessageBody *)dbMsgBody {
    if (msgBody.type == AgoraChatMessageBodyTypeText) {
        AgoraChatTextMessageBody *body = (AgoraChatTextMessageBody *)msgBody;
        AgoraChatTextMessageBody *dbBody = (AgoraChatTextMessageBody *)dbMsgBody;
        dbBody.targetLanguages = body.targetLanguages;
    } else if (msgBody.type == AgoraChatMessageBodyTypeImage) {
        AgoraChatImageMessageBody *body = (AgoraChatImageMessageBody *)msgBody;
        AgoraChatImageMessageBody *dbBody = (AgoraChatImageMessageBody *)dbMsgBody;
        dbBody.displayName = body.displayName;
        dbBody.localPath = body.localPath;
        dbBody.remotePath = body.remotePath;
        dbBody.secretKey = body.secretKey;
        dbBody.fileLength = body.fileLength;
        dbBody.downloadStatus = body.downloadStatus;
        dbBody.size = body.size;
        dbBody.compressionRatio = body.compressionRatio;
        dbBody.thumbnailDisplayName = body.thumbnailDisplayName;
        dbBody.thumbnailLocalPath = body.thumbnailLocalPath;
        dbBody.thumbnailRemotePath = body.thumbnailRemotePath;
        dbBody.thumbnailSecretKey = body.thumbnailSecretKey;
        dbBody.thumbnailSize = body.thumbnailSize;
        dbBody.thumbnailFileLength = body.thumbnailFileLength;
        dbBody.thumbnailDownloadStatus = body.thumbnailDownloadStatus;
    } else if (msgBody.type == AgoraChatMessageBodyTypeVideo) {
        AgoraChatVideoMessageBody *body = (AgoraChatVideoMessageBody *)msgBody;
        AgoraChatVideoMessageBody *dbBody = (AgoraChatVideoMessageBody *)dbMsgBody;
        dbBody.displayName = body.displayName;
        dbBody.localPath = body.localPath;
        dbBody.remotePath = body.remotePath;
        dbBody.secretKey = body.secretKey;
        dbBody.fileLength = body.fileLength;
        dbBody.downloadStatus = body.downloadStatus;
        dbBody.duration = body.duration;
        dbBody.thumbnailLocalPath = body.thumbnailLocalPath;
        dbBody.thumbnailRemotePath = body.thumbnailRemotePath;
        dbBody.thumbnailSecretKey = body.thumbnailSecretKey;
        dbBody.thumbnailSize = body.thumbnailSize;
        dbBody.thumbnailDownloadStatus = body.thumbnailDownloadStatus;
    } else if (msgBody.type == AgoraChatMessageBodyTypeLocation) {
        AgoraChatLocationMessageBody *body = (AgoraChatLocationMessageBody *)msgBody;
        AgoraChatLocationMessageBody *dbBody = (AgoraChatLocationMessageBody *)dbMsgBody;
        dbBody.latitude = body.latitude;
        dbBody.longitude = body.longitude;
        dbBody.address = body.address;
        dbBody.buildingName = body.buildingName;
    } else if (msgBody.type == AgoraChatMessageBodyTypeVoice) {
        AgoraChatVoiceMessageBody *body = (AgoraChatVoiceMessageBody *)msgBody;
        AgoraChatVoiceMessageBody *dbBody = (AgoraChatVoiceMessageBody *)dbMsgBody;
        dbBody.displayName = body.displayName;
        dbBody.localPath = body.localPath;
        dbBody.remotePath = body.remotePath;
        dbBody.secretKey = body.secretKey;
        dbBody.fileLength = body.fileLength;
        dbBody.downloadStatus = body.downloadStatus;
        dbBody.duration = body.duration;
    } else if (msgBody.type == AgoraChatMessageBodyTypeFile) {
        AgoraChatFileMessageBody *body = (AgoraChatFileMessageBody *)msgBody;
        AgoraChatFileMessageBody *dbBody = (AgoraChatFileMessageBody *)dbMsgBody;
        dbBody.displayName = body.displayName;
        dbBody.localPath = body.localPath;
        dbBody.remotePath = body.remotePath;
        dbBody.secretKey = body.secretKey;
        dbBody.fileLength = body.fileLength;
        dbBody.downloadStatus = body.downloadStatus;
    } else if (msgBody.type == AgoraChatMessageBodyTypeCmd) {
        AgoraChatCmdMessageBody *body = (AgoraChatCmdMessageBody *)msgBody;
        AgoraChatCmdMessageBody *dbBody = (AgoraChatCmdMessageBody *)dbMsgBody;
        dbBody.action = body.action;
        dbBody.isDeliverOnlineOnly = body.isDeliverOnlineOnly;
    } else if (msgBody.type == AgoraChatMessageBodyTypeCustom) {
        AgoraChatCustomMessageBody *body = (AgoraChatCustomMessageBody *)msgBody;
        AgoraChatCustomMessageBody *dbBody = (AgoraChatCustomMessageBody *)dbMsgBody;
        dbBody.event = body.event;
        dbBody.customExt = body.customExt;
    } else if (msgBody.type == AgoraChatMessageBodyTypeCombine) {
        AgoraChatCombineMessageBody *body = (AgoraChatCombineMessageBody *)msgBody;
        AgoraChatCombineMessageBody *dbBody = (AgoraChatCombineMessageBody *)dbMsgBody;
        dbBody.title = body.title;
        dbBody.summary = body.summary;
        dbBody.compatibleText = body.compatibleText;
    }
}

- (void)mergeMessage:(AgoraChatMessage *)msg withDBMessage:(AgoraChatMessage *)dbMsg {

    //    dbMsg.messageId = msg.messageId;
    //    dbMsg.conversationId = msg.conversationId;
    //    dbMsg.chatType = msg.chatType;
    //
    //    dbMsg.from = msg.from;
    //    dbMsg.to = msg.to;
    //    dbMsg.direction = msg.direction;

    dbMsg.timestamp = msg.timestamp;
    dbMsg.localTime = msg.localTime;
    dbMsg.status = msg.status;
    dbMsg.isReadAcked = msg.isReadAcked;
    dbMsg.isChatThreadMessage = msg.isChatThreadMessage;
    dbMsg.isNeedGroupAck = msg.isNeedGroupAck;
    dbMsg.isDeliverAcked = msg.isDeliverAcked;
    dbMsg.isRead = msg.isRead;
    dbMsg.isListened = msg.isListened;
    dbMsg.receiverList = msg.receiverList;
    dbMsg.priority = msg.priority;
    dbMsg.deliverOnlineOnly = msg.deliverOnlineOnly;
    dbMsg.ext = msg.ext;
    //    AgoraChatMessageBody *newBody = [self mergeMessageBody:msg.body
    //    withDBMessageBody:dbMsg.body];
    dbMsg.body = msg.body;
}

- (AgoraChatConversation *)getConversation:(NSDictionary *)param {
    NSString *convId = param[@"convId"];
    AgoraChatConversationType convType =
        [AgoraChatConversation typeFromInt:[param[@"convType"] intValue]];
    BOOL isChatThread =
        param[@"isChatThread"] ? [param[@"isChatThread"] boolValue] : NO;
    BOOL createIfNotExist =
        param[@"createIfNeed"] ? [param[@"createIfNeed"] boolValue] : YES;
    return [[AgoraChatClient.sharedClient chatManager] getConversation:convId
                                                           type:convType
                                               createIfNotExist:createIfNotExist
                                                       isThread:isChatThread];
}

- (AgoraChatConversation *)getConversationFromMessage:(AgoraChatMessage *)msg {
    BOOL createIfNotExist = msg.body.type != AgoraChatMessageBodyTypeCmd;
    return [[AgoraChatClient.sharedClient chatManager]
         getConversation:msg.conversationId
                    type:(AgoraChatConversationType)msg.chatType
        createIfNotExist:createIfNotExist
                isThread:msg.isChatThreadMessage];
}

@end
