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

#import "BusStatusInfoResultViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "Collectors.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "DZNEmptyDataSetDefault.h"
#import <BlocksKit/BlocksKit.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "BusStatusInfo.h"
#import "TrackBusStatusResponseJsonMapper.h"
#import "BusStatusDetailViewController.h"
#import "Vars.h"

@interface BusStatusInfoResultViewController () <DZNEmptyDataSetDefault>
@property (nonatomic, strong) NSArray *busStatusInfos;
@property (nonatomic, strong) NSArray *cellDataArray;
@end

@implementation BusStatusInfoResultViewController

- (instancetype)init {
	if (self = [super init]) {
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	self.title = self.departureDateText;

	self.tableView.estimatedRowHeight = 60;
	self.tableView.emptyDataSetSource = self;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	if (!self.busStatusInfos) {
		[self trackBusStatus];
	}
}

#pragma mark - Segue

- (void)performSegueForBusStatusDetailWithProduct:(Product *)product {
	BusStatusDetailViewController *viewController = [[BusStatusDetailViewController alloc] init];
	viewController.departureDate = self.departureDateText;
	viewController.product = product;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Network

- (void)trackBusStatus {
	TrackBusStatus *trackBusStatus = [[TrackBusStatus alloc] init];
	trackBusStatus.serviceDate = self.departureDateText;
	if (!self.isByCities) {
		trackBusStatus.scheduleId = self.scheduleIdText;
	} else {
		trackBusStatus.departureCity = self.departureText;
		trackBusStatus.arrivalCity = self.arrivalText;
	}
	self.tableView.emptyDataSetSource = nil;
	NSDictionary *requestDict = [Utility perlParamXml:[trackBusStatus innerXML] action:trackBusStatus.name];
	// NSLog(@"%@", requestDict);
	[Utility getXMLFromRequestWithMethod:@"GET" url:trackBusStatus.address parameters:requestDict success:^(NSString *xml) {
		NSString *responesStr = xml;
		// NSLog(@"%@", responesStr);
		TrackBusStatusResponseJsonMapper *mapper = [[TrackBusStatusResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responesStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			TrackBusStatusResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				self.busStatusInfos = response.bus_status_infos;
				[self buildCellDataSource];
				self.tableView.emptyDataSetSource = self;
				[self.tableView reloadData];
			}
		}
	}];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	for (BusStatusInfo *busStatusInfo in self.busStatusInfos) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.text = busStatusInfo.product.name;
		data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
		data.detailAttributedText = [self buildContentWithRow:busStatusInfo];
		data.detailTextFont = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption2];
		data.allowsDetailTextLineWrapping = YES;
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForBusStatusDetailWithProduct: busStatusInfo.product];
		}];
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

- (NSAttributedString *)buildContentWithRow:(BusStatusInfo *)statusInfo {
	Product *product = statusInfo.product;
	NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Bus ID" attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:product.schedule_id]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
	Vendor *vendor = product.vendor_obj;
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Bus Operator" attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:vendor.short_name]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Bus Status" attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
	[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:statusInfo.statusName attributes:@{ NSForegroundColorAttributeName : statusInfo.statusColor }]];
	if (![StringUtils isEmpty:statusInfo.otherDescription]) {
		[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
		[string appendAttributedString:[[NSAttributedString alloc] im_initWithString:statusInfo.otherDescription attributes:@{ NSForegroundColorAttributeName : [UIColor darkGrayColor] }]];
	}
	return [[NSAttributedString alloc] initWithAttributedString:string];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.cellDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

@end
