//
// ScheduleBusRouteListResponseJsonMapper.m
// Project
//
// Created by Ziv on 2017/4/10.
//
//

#import "BookingReportScheduleListResponseJsonMapper.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import <RestKit/RKObjectMappingOperationDataSource.h>
#import "Schedule.h"
#import "Route.h"
#import <RestKit/RestKit.h>

@implementation BookingReportScheduleListResponseJsonMapper

- (instancetype)init {
	if (self = [super init]) {
		RKObjectMapping *scheduleMapping = [[RKObjectMapping alloc] initWithClass:[Schedule class]];
		[scheduleMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Schedule class]]];
        
		RKObjectMapping *routeMapping = [[RKObjectMapping alloc] initWithClass:[Route class]];
		[routeMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[Route class]]];
        [routeMapping addRelationshipMappingWithSourceKeyPath:@"schedules" mapping:scheduleMapping];
        [routeMapping addRelationshipMappingWithSourceKeyPath:@"stopSchedules" mapping:scheduleMapping];

		RKObjectMapping *responseMapping = [[RKObjectMapping alloc] initWithClass:[BookingReportResponse class]];
		[responseMapping addAttributeMappingsFromArray:[BeanUtils keysForAccessibleSimplePropertyWithClass:[BookingReportResponse class]]];
		[responseMapping addRelationshipMappingWithSourceKeyPath:@"routeList" mapping:routeMapping];

		self.objectMapping = responseMapping;
	}
	return self;
}

#pragma mark - Public

- (NSError *)parseWithJSONObject:(id)jsonObject {
	self.response = [[BookingReportResponse 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]) {
		for (Route *route in self.response.routeList) {
			for (Schedule *schedule in route.schedules) {
				schedule.route = route;
			}
		}
	}
	return error;
}

@end
