//
//  MBIMSendMessageOperation.m
//  kordophoned
//
//  Created by James Magahern on 11/13/18.
//  Copyright © 2018 James Magahern. All rights reserved.
//

#import "MBIMSendMessageOperation.h"

#import "IMCore_ClassDump.h"
#import "IMMessageItem+Encoded.h"

@implementation MBIMSendMessageOperation

+ (void)load { [super load]; }

+ (NSString *)endpointName
{
    return @"sendMessage";
}

- (IMMessage *)_sendMessage:(NSString *)messageBody toChatWithGUID:(NSString *)chatGUID attachmentGUIDs:(NSArray<NSString *> *)guids
{
    __block IMMessage *result = nil;
    
    dispatch_sync([[self class] sharedIMAccessQueue], ^{
        IMChat *chat = [[IMChatRegistry sharedInstance] existingChatWithGUID:chatGUID];
        
        // TODO: chat might not be an iMessage chat!
        IMAccount *iMessageAccount = [[IMAccountController sharedInstance] bestAccountForService:[IMServiceImpl iMessageService]];
        IMHandle *senderHandle = [iMessageAccount loginIMHandle];
        
        NSAttributedString *replyAttrString = [[NSAttributedString alloc] initWithString:messageBody];
        NSAttributedString *attrStringWithFileTransfers = IMCreateSuperFormatStringWithAppendedFileTransfers(replyAttrString, guids);
        
        IMMessage *reply = [IMMessage fromMeIMHandle:senderHandle
                                            withText:attrStringWithFileTransfers
                                   fileTransferGUIDs:guids
                                               flags:(kIMMessageFinished | kIMMessageIsFromMe)];
        
        for (NSString *guid in [reply fileTransferGUIDs]) {
            [[IMFileTransferCenter sharedInstance] assignTransfer:guid toHandle:chat.recipient];
        }
        
        if (!chat) {
            MBIMLogInfo(@"Chat does not exist: %@", chatGUID);
        } else {
            result = reply;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [chat sendMessage:reply];
            });
        }
    });
    
    return result;
}

#if 0
- (NSDictionary *)adjustMessageSummaryInfoForSending:(NSDictionary *)messageSummaryInfo
{
    NSMutableDictionary *adjustedInfo = [messageSummaryInfo mutableCopy];
    if (!adjustedInfo) {
        adjustedInfo = [NSMutableDictionary dictionary];
    }

    if ([fullText length] > 50) {
        summary = [[summary substringToIndex:[summary rangeOfComposedCharacterSequenceAtIndex:kMaxSummaryLength].location] stringByAppendingString:@"…"];
        adjustedInfo[IMMessageSummaryInfoSummary] = summary;
    }

    
    adjustedInfo[IMMessageSummaryInfoTapbackRepresentationKey] = @"Loved";

    return adjustedInfo;
}
#endif

- (void)main
{
    NSObject<HTTPResponse> *response = [[HTTPErrorResponse alloc] initWithErrorCode:500];
    
    NSError *error = nil;
    NSDictionary *args = [NSJSONSerialization JSONObjectWithData:self.requestBodyData options:0 error:&error];
    if (error || args.count == 0) {
        self.serverCompletionBlock(response);
        return;
    }
    
    NSString *guid = [args objectForKey:@"guid"];
    NSString *messageBody = [args objectForKey:@"body"];
    if (!guid || !messageBody) {
        self.serverCompletionBlock(response);
        return;
    }
    
    // tapbacks
#if 0
    IMMessage *acknowledgment = [IMMessage instantMessageWithAssociatedMessageContent: /* [NSString stringWithFormat:@"%@ \"%%@\"", tapbackAction] */
                                                                                flags:0
                                                                associatedMessageGUID:guid
                                                                associatedMessageType:IMAssociatedMessageTypeAcknowledgmentHeart
                                                               associatedMessageRange:[imMessage messagePartRange]
                                                                   messageSummaryInfo:[self adjustMessageSummaryInfoForSending:message]
                                                                     threadIdentifier:[imMessage threadIdentifier]];
#endif
    
    NSArray *transferGUIDs = [args objectForKey:@"fileTransferGUIDs"];
    if (!transferGUIDs) {
        transferGUIDs = @[];
    }
    
    IMMessage *result = [self _sendMessage:messageBody toChatWithGUID:guid attachmentGUIDs:transferGUIDs];
    if (result) {
        response = [MBIMJSONDataResponse responseWithJSONObject:[result mbim_dictionaryRepresentation]];
    }
    
    self.serverCompletionBlock(response);
}

@end
