//
// Copyright 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//

#import "OWSGroupCallMessage.h"
#import "FunctionalUtil.h"
#import "TSGroupThread.h"
#import <SignalCoreKit/NSDate+OWS.h>
#import <SignalServiceKit/SignalServiceKit-Swift.h>

NS_ASSUME_NONNULL_BEGIN

#pragma mark -

@implementation OWSGroupCallMessage

- (instancetype)initWithJoinedMemberAcis:(NSArray<AciObjC *> *)joinedMemberAcis
                              creatorAci:(nullable AciObjC *)creatorAci
                                  thread:(TSGroupThread *)thread
                         sentAtTimestamp:(uint64_t)sentAtTimestamp
{
    self = [super initInteractionWithTimestamp:sentAtTimestamp thread:thread];

    if (!self) {
        return self;
    }

    _joinedMemberUuids = [joinedMemberAcis map:^(AciObjC *aci) { return aci.serviceIdUppercaseString; }];
    _hasEnded = joinedMemberAcis.count == 0;
    _creatorUuid = creatorAci.serviceIdUppercaseString;

    return self;
}

// --- CODE GENERATION MARKER

// This snippet is generated by /Scripts/sds_codegen/sds_generate.py. Do not manually edit it, instead run
// `sds_codegen.sh`.

// clang-format off

- (instancetype)initWithGrdbId:(int64_t)grdbId
                      uniqueId:(NSString *)uniqueId
             receivedAtTimestamp:(uint64_t)receivedAtTimestamp
                          sortId:(uint64_t)sortId
                       timestamp:(uint64_t)timestamp
                  uniqueThreadId:(NSString *)uniqueThreadId
                     creatorUuid:(nullable NSString *)creatorUuid
                           eraId:(nullable NSString *)eraId
                        hasEnded:(BOOL)hasEnded
               joinedMemberUuids:(nullable NSArray<NSString *> *)joinedMemberUuids
                            read:(BOOL)read
{
    self = [super initWithGrdbId:grdbId
                        uniqueId:uniqueId
               receivedAtTimestamp:receivedAtTimestamp
                            sortId:sortId
                         timestamp:timestamp
                    uniqueThreadId:uniqueThreadId];

    if (!self) {
        return self;
    }

    _creatorUuid = creatorUuid;
    _eraId = eraId;
    _hasEnded = hasEnded;
    _joinedMemberUuids = joinedMemberUuids;
    _read = read;

    return self;
}

// clang-format on

// --- CODE GENERATION MARKER

- (nullable instancetype)initWithCoder:(NSCoder *)coder
{
    return [super initWithCoder:coder];
}

- (NSArray<AciObjC *> *)joinedMemberAcis
{
    return [(self.joinedMemberUuids ?: @[]) map:^(
        NSString *aciString) { return [[AciObjC alloc] initWithAciString:aciString]; }];
}

- (nullable AciObjC *)creatorAci
{
    if (self.creatorUuid) {
        return [[AciObjC alloc] initWithAciString:self.creatorUuid];
    } else {
        return nil;
    }
}

- (OWSInteractionType)interactionType
{
    return OWSInteractionType_Call;
}

@end

NS_ASSUME_NONNULL_END
