//
// TrackBusStatusJsonMapper.m
// LiveProject
//
// Created by Ziv on 15/8/28.
//
//

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

@interface TrackBusStatusResponseJsonMapper ()
@end

@implementation TrackBusStatusResponseJsonMapper

- (instancetype)init {
	if (self = [super init]) {
		RKObjectMapping *busStatusInfoMapping = [RKObjectMapping mappingForClass:[BusStatusInfo class]];
		[busStatusInfoMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[BusStatusInfo class]]];

		RKObjectMapping *productMapping = [RKObjectMapping mappingForClass:[Product class]];
		[productMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Product class]]];

		RKObjectMapping *vendorMapping = [RKObjectMapping mappingForClass:[Vendor class]];
		[vendorMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Vendor class]]];

		RKObjectMapping *trackBusStatusMapping = [RKObjectMapping mappingForClass:[TrackBusStatusResponse class]];
		[trackBusStatusMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[TrackBusStatusResponse class]]];
		[trackBusStatusMapping addRelationshipMappingWithSourceKeyPath:@"bus_status_infos" mapping:busStatusInfoMapping];
		[trackBusStatusMapping addRelationshipMappingWithSourceKeyPath:@"products" mapping:productMapping];
		[trackBusStatusMapping addRelationshipMappingWithSourceKeyPath:@"vendors" mapping:vendorMapping];

		self.objectMapping = trackBusStatusMapping;
	}
	return self;
}

#pragma mark - Public

- (NSError *)parseWithJSONObject:(id)jsonObject {
	self.response = [[TrackBusStatusResponse 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;
	if ([mappingOperation performMapping:&error]) {
		NSArray *busStatusInfos = self.response.bus_status_infos;
		NSArray *products = self.response.products;
		NSArray *vendors = self.response.vendors;
		NSDictionary *vendorHash = [NSDictionary dictionaryWithObjects:vendors forKeys:[vendors valueForKeyPath:@"id"]];
		for (Product *product in products) {
			product.vendor_obj = vendorHash[@(product.vendor)];
		}
		NSDictionary *productHash = [NSDictionary dictionaryWithObjects:products forKeys:[products valueForKey:@"product_id"]];
		for (BusStatusInfo *statusInfo in busStatusInfos) {
			statusInfo.product = productHash[@(statusInfo.pid)];
		}
	}
	return error;
}

@end
