//
//  MessageResponseJsonMapper.m
//  Project
//
//  Created by 包光清 on 2019/1/24.
//

#import "MessageResponseJsonMapper.h"
#import <RestKit/RKObjectMappingOperationDataSource.h>
#import "CocoaUtils.h"
#import "BeanUtils.h"
#import "NotificationApi.h"
#import "Message.h"
#import "NotificationData.h"


@implementation MessageResponseJsonMapper
- (instancetype)init {
	if (self = [super init]) {
		RKObjectMapping *notificationMapping = [[RKObjectMapping alloc] initWithClass:[NotificationData class]];
		[notificationMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[NotificationData class]]];
		
		RKObjectMapping *messageMapping = [[RKObjectMapping alloc] initWithClass:[Message class]];
		[messageMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Message class]]];
		[messageMapping addRelationshipMappingWithSourceKeyPath:@"data" mapping:notificationMapping];
		
		RKObjectMapping *responseMapping = [[RKObjectMapping alloc] initWithClass:[GetUserMessagesResponse class]];
		[responseMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[GetUserMessagesResponse class]]];
		[responseMapping addRelationshipMappingWithSourceKeyPath:@"messages" mapping:messageMapping];
		
		self.objectMapping = responseMapping;
	}
	return self;
}

- (NSError *)parseWithJSONObject:(id)jsonObject {
	self.response = [[GetUserMessagesResponse alloc] init];
	
	RKMappingOperation *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:jsonObject destinationObject:self.response mapping:self.objectMapping];
	RKObjectMappingOperationDataSource *mappingOperationDataSource = [[RKObjectMappingOperationDataSource alloc] init];
	mappingOperation.dataSource = mappingOperationDataSource;
	
	NSError *error = nil;
	[mappingOperation performMapping:&error];
	return error;
}
@end
