//
// RegistrationResponseJsonMapper.m
// LiveProject
//
// Created by Ziv on 15/9/21.
//
//

#import "RegistrationResponseJsonMapper.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import <RestKit/RestKit.h>
#import <RestKit/RKObjectMappingOperationDataSource.h>

@implementation RegistrationResponseJsonMapper

- (instancetype)init {
	if (self = [super init]) {
		RKObjectMapping *vendorMapping = [RKObjectMapping mappingForClass:[Vendor class]];
		[vendorMapping addAttributeMappingsFromDictionary:[CocoaUtils dictionaryForKeys:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Vendor class]] retainEntries:@{ @"userId" : @"id", @"userName" : @"uid" }]];

		RKObjectMapping *registrationMapping = [RKObjectMapping mappingForClass:[RegistrationResponse class]];
		[registrationMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[RegistrationResponse class]]];
		[registrationMapping addRelationshipMappingWithSourceKeyPath:@"user" mapping:vendorMapping];

		self.objectMapping = registrationMapping;
	}
	return self;
}

#pragma mark - Public

- (NSError *)parseWithJSONObject:(id)jsonObject {
	self.response = [[RegistrationResponse 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
