//
//  Message+DictRepresentation.m
//  rainbow
//
//  Created by Doha Tubaileh on 10/3/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "Message+DictRepresentation.h"
#import "CallLog+CallStateToReactConverter.h"
#import "NSDate+ReactDateFormatter.h"
#import "NSData+Base64String.h"
#import "NSString+PictureData.h"
#import "Contact+DictRepresentation.h"
#import "DefaultFileIcon.h"
#import "Rainbow/Rainbow.h"
#import "Messages.h"



@implementation Message (DictRepresentation)
-(NSDictionary*)messageDictionaryRepresentation {
    NSLog(@"messageDictionaryRepresentation with messageId: %@", self.messageID);
    NSMutableDictionary *messageDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *msgOwnerDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *msgConferenceDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *msgCallLogDic = [[NSMutableDictionary alloc] init];
    id createdAt = self.date.changeDateFormatToReact;
    [messageDic setObject:self.messageID forKey:@"_id"];
    [messageDic setObject:[self getMessegeText] forKey:@"text"];
    [messageDic setObject:[NSNumber numberWithBool:self.isOutgoing] forKey:@"isSent"];
    [messageDic setObject:[self convertStateForReact] forKey:@"msgDeliveryStatus"];
    [messageDic setObject:[self getAssociatedMessageId] forKey:@"associatedMsgId"];
    [messageDic setObject:[self getMessageType] forKey:@"msgType"];
       if (createdAt) {
        [messageDic setObject:createdAt forKey:@"createdAt"];
    }
    id<PeerProtocol> peerObject = self.peer;
    RainbowContact *peerAsContact = (RainbowContact*) peerObject;
    MyUser *myUser =[ServicesManager.sharedInstance myUser];
    BOOL isMyMsg = [peerObject.jid isEqual:myUser.contact.jid];

    if ([peerAsContact class] == [RainbowContact class]){
        [msgOwnerDic setObject:peerAsContact.displayName forKey:@"name"];
        if(peerAsContact.photoData != nil){
            NSString *serverName = [ServicesManager.sharedInstance myUser].server.serverDisplayedName;
            NSString *imageURL = [NSString stringWithFormat:@"https://%@/api/avatar/%@?size=256", serverName, peerObject.rainbowID];
            [msgOwnerDic setObject:imageURL forKey:@"avatar"];
        }
        [msgOwnerDic setObject:self.isOutgoing?@"sent":peerObject.jid forKey:@"_id"];
    
        [msgOwnerDic setObject:[NSNumber numberWithBool:isMyMsg] forKey:@"isMyMsg"];
    }
    [messageDic setObject:msgOwnerDic forKey:@"user"];

    if (self.type == MessageTypeWebRTC) {
        [messageDic setObject:@YES forKey:@"system"];
        [msgCallLogDic setValue:self.body forKey:@"msgContent"];
        [messageDic setObject:msgCallLogDic forKey:@"call"];
    }
    if (self.type == MessageTypeGroupChatEvent) {
        [messageDic setObject:@YES forKey:@"system"];
        [msgConferenceDic setValue:self.body forKey:@"msgContent"];
        [messageDic setObject:msgConferenceDic forKey:@"conference"];
    }
    //check if the msg has file
    if (self.attachment != nil && !self.isDeleted) {
        [messageDic setObject:self.attachment.rainbowID==nil?[NSNull null]:self.attachment.rainbowID forKey:@"fileDescriptorId"];
        [messageDic setObject:[self getFileBase64:self.attachment] forKey:@"image"];
    }
    if (self.alternateBody.count > 0) {
        NSArray *alternativeContentsArray = [self processMessageAlternateBody];
        [messageDic setObject:alternativeContentsArray forKey:@"alternativeContent"];
    }
    [messageDic setObject:[self getMsgUrgency] forKey:@"urgency"];
    [messageDic setObject:[NSNumber numberWithBool:self.isDeleted] forKey:@"isDeleted"];
    [messageDic setObject:[NSNumber numberWithBool:self.answeredMessageId != nil] forKey:@"isReplied"];
    [messageDic setObject:[NSNumber numberWithBool:self.isForwarded] forKey:@"isForwarded"];

    return messageDic;
}


-(NSString*)getFileBase64:(File*)attachment {
    NSString *fileImageBase64 = @"data:image/png;base64,";
        //check if the file is image
        if (self.attachment.type == FileTypeImage && self.attachment.thumbnailData != nil ) {
            fileImageBase64 = [fileImageBase64 stringByAppendingString:self.attachment.thumbnailData.encodeToBase64String];
        }
        else {//any file type
            fileImageBase64 = @"icon";
        }
    return fileImageBase64;
}

-(NSString*)convertStateForReact {
    switch (self.state) {
        case MessageDeliveryStateSent:
            return @"SENT";
        case MessageDeliveryStateDelivered://Delivered
            return @"SENT_CLIENT_RECEIVED";
        case MessageDeliveryStateReceived:
            return @"RECEIVED";
        case MessageDeliveryStateRead:
            return @"READ";
        default:
            return @"UNKNOWN";
    }
}

-(NSString*) getMsgUrgency {
    switch (self.priority) {
        case MessagePriorityLow:
            return @"LOW";
            break;
        case MessagePriorityMiddle:
            return @"MEDIUM";
            break;
        case MessagePriorityHigh:
            return @"HIGH";
            break;
        default:
            return @"NONE";
            break;
    }
}

-(NSString*) getAssociatedMessageId {
    if (self.answeredMessageId != nil) {
        return self.answeredMessageId;
    }
    return @"";
}

-(NSArray*) processMessageAlternateBody {
    NSMutableArray *alternativeContentsArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.alternateBody.count; i++) {
        MessageContent *currentBody = self.alternateBody[0];
        NSMutableDictionary *alternateBodyDict = [[NSMutableDictionary alloc] init];
        [alternateBodyDict setObject:currentBody.contentType forKey:@"contentType"];
        [alternateBodyDict setObject:currentBody.contentBody forKey:@"contentBody"];
        [alternativeContentsArray addObject:alternateBodyDict];
    }

    return alternativeContentsArray;
}


-(NSString*) getMessageType {

    if (self.isForwarded) {
        return @"FORWARD";
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.contentType == %@",@"form/json"];

    if ([self.alternateBody filteredArrayUsingPredicate:predicate].count) {
        return @"FORM";
    }
    if (self.attachment) {
        return @"FILE";
    }

    switch (self.type) {
        case MessageTypeWebRTCStart:
        case MessageTypeWebRTCRinging:
        case MessageTypeWebRTC :
            return @"WebRTC_CAll";

        case MessageTypeFileTransfer:
            return @"FileSharing";

        case MessageTypeCallRecordingStart:
        case MessageTypeCallRecordingStop:
            return @"Recording";

        case MessageTypeChat:
            return @"Chat";

        default: return @"Unknown";

    }


}

-(NSString*) getMessegeText {
    if ((self.attachment && self.attachment.type == FileTypeImage) || self.body == nil) {
            return @"";
        }
    return self.body;
}

@end
