//
//  GetGoogleLoginResponseJsonMapper.m
//  
//
//  Created by 包光清 on 2018/9/4.
//

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

@implementation GoogleLoginResponseJsonMapper

- (instancetype)init {
	if (self = [super init]) {
		RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[Address class]];
		[addressMapping addAttributeMappingsFromDictionary:[CocoaUtils dictionaryForKeys:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Address class]] retainEntries:@{ @"firstName" : @"first_name", @"lastName" : @"last_name", @"isDefaultAddress" : @"isDefault" }]];
		RKObjectMapping *creditMapping = [RKObjectMapping mappingForClass:[CreditCard class]];
		[creditMapping addAttributeMappingsFromDictionary:[CocoaUtils dictionaryForKeys:[BeanUtils keysForAccessibleSimplePropertyWithClass:[CreditCard class]] retainEntries:@{ @"cardType" : @"card_type", @"displayCardNumber" : @"card_number", @"expireYear" : @"expire_year", @"expireMonth" : @"expire_month" , @"nameOnCard" : @"name_on_card", @"xCardCode" : @"x_card_code"}]];
		[creditMapping addRelationshipMappingWithSourceKeyPath:@"address" mapping:addressMapping];
		
		RKObjectMapping *vendorMapping = [RKObjectMapping mappingForClass:[Vendor class]];
		[vendorMapping addAttributeMappingsFromDictionary:[CocoaUtils dictionaryForKeys:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Vendor class]] retainEntries:@{ @"blockStatus" : @"block_status", @"cookieString" : @"cookie_string", @"upcomingItinerariesCount" : @"upcoming_itineraries_count", @"appFirstPurchaseDiscountBannerShown" : @"app_first_purchase_discount_banner_shown" ,@"userAppId" : @"user_app_id"}]];
		[vendorMapping addRelationshipMappingWithSourceKeyPath:@"creditCards" mapping:creditMapping];
		[vendorMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"userAddresses" toKeyPath:@"contactInfos" withMapping:addressMapping]];
		
		RKObjectMapping *loginMapping = [RKObjectMapping mappingForClass:[GoogleLoginResponse class]];
		[loginMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[GoogleLoginResponse class]]];
		[loginMapping addRelationshipMappingWithSourceKeyPath:@"user" mapping:vendorMapping];
		
		self.objectMapping = loginMapping;
	}
	return self;
}

#pragma mark - Public

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