//  CustomMessage.m


#import "CustomMessage.h"

@implementation CustomMessage

///初始化
+ (instancetype)messageWithGiftName:(NSString *)giftName GiftCount:(int) giftCount {
    CustomMessage *msg = [[CustomMessage alloc] init];
    if (msg) {
        msg.giftName = giftName;
        msg.giftCount = giftCount;
    }
    return msg;
}

///消息是否存储，是否计入未读数
+ (RCMessagePersistent)persistentFlag {
    return MessagePersistent_ISCOUNTED;
}

/// NSCoding
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.giftName = [aDecoder decodeObjectForKey:@"giftName"];
        self.extra = [aDecoder decodeObjectForKey:@"extra"];
    }
    return self;
}

/// NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.giftName forKey:@"giftName"];
    [aCoder encodeObject:self.extra forKey:@"extra"];
}

///将消息内容编码成json
- (NSData *)encode {
    NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
    [dataDict setObject:self.giftName forKey:@"giftName"];
    [dataDict setObject:[NSString stringWithFormat:@"%d",self.giftCount] forKey:@"giftCount"];
    if (self.extra) {
        [dataDict setObject:self.extra forKey:@"extra"];
    }
    //处理用户信息
    if (self.senderUserInfo) {
        [dataDict setObject:[self encodeUserInfo:self.senderUserInfo] forKey:@"user"];
    }

    NSData *data = [NSJSONSerialization dataWithJSONObject:dataDict options:kNilOptions error:nil];
    return data;
}


///将json解码生成消息内容
- (void)decodeWithData:(NSData *)data {
    if (data) {
        __autoreleasing NSError *error = nil;

        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        if (dictionary) {
            self.giftName = dictionary[@"giftName"];
            self.giftCount = [dictionary[@"giftCount"] intValue];
            self.extra = dictionary[@"extra"];

            NSDictionary *userinfoDic = dictionary[@"user"];
            [self decodeUserInfo:userinfoDic];
        }
    }
}

/// 会话列表中显示的摘要
- (NSString *)conversationDigest {
    return self.giftName;
}

///消息的类型名
+ (NSString *)getObjectName {
    return @"gift:CustomMsg";
}

@end
