//
//  IMChat+Encoded.m
//  kordophoned
//
//  Created by James Magahern on 11/19/18.
//  Copyright © 2018 James Magahern. All rights reserved.
//

#import "IMChat+Encoded.h"
#import "IMMessageItem+Encoded.h"
#import "MBIMHTTPUtilities.h"

@implementation IMChat (Encoded)

- (NSDictionary *)mbim_dictionaryRepresentation
{
    NSMutableDictionary *chatDict = [NSMutableDictionary dictionary];
    chatDict[@"guid"] = [self guid];
    chatDict[@"displayName"] = [self displayName];
    chatDict[@"date"] = MBIMWebServerFormatISO8601([self lastFinishedMessageDate]);
    chatDict[@"unreadCount"] = @([self unreadMessageCount]);
    
    // NOTE: -[IMChat lastMessage] != -[[IMChat chatItems] lastMessage].
    // This means the messages we get back from the message list operation might be different from this here, which means we
    // can't reliably use `lastMessage.guid` as a sync anchor.
    //
    // Ideally, everything should move to use chat items instead of messages so we can handle associated message items (reactions).
    // When that happens, we should use `lastFinishedMessageItem` here instead of `lastMessage`, and avoid the db hit.
    //
    IMMessage *lastMessage = [self lastMessage];
    if (lastMessage) {
        NSString *lastMessagePreview = [lastMessage descriptionForPurpose:IMMessageDescriptionConversationList];
        chatDict[@"lastMessagePreview"] = [lastMessagePreview substringToIndex:MIN(128, [lastMessagePreview length])];
        chatDict[@"lastMessage"] = [lastMessage mbim_dictionaryRepresentation];
    }
    
    NSMutableArray *participantStrings = [NSMutableArray array];
    for (IMHandle *participantHandle in self.participants) {
        NSString *participantString = [participantHandle displayNameForChat:self];
        if (participantString) {
            [participantStrings addObject:participantString];
        }
    }
    
    chatDict[@"participantDisplayNames"] = participantStrings;
    
    return chatDict;
}

@end
