//
//  FilterViewController.m
//  Project
//
//  Created by Vae on 2018/11/5.
//

#import "FilterViewController.h"
#import "Vars.h"
#import "JSBusSiteBridge.h"
#import "SDK.h"
#import <dsBridge/dsbridge.h>
#import <YYModel/YYModel.h>
#import <libextobjc/EXTScope.h>
#import <BlocksKit/BlocksKit.h>

@interface FilterViewController ()
@property(nonatomic, strong) DWKWebView *webView;
@property (nonatomic, copy) void (^didDoneBlock) (void);
@property(nonatomic, copy) NSInteger (^filterSearchListBlock)(FilterData *filterData);
@end

@implementation FilterViewController

- (instancetype)init {
	if ((self = [super init])) {
		// Custom initialization
		self.title = @"Filter";
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	@weakify(self)
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] im_initWithTitle:@"Done" style:UIBarButtonItemStyleDone handler:^(UIBarButtonItem *barButtonItem) {
		@strongify(self)
		self.didDoneBlock();
		[self.navigationController popViewControllerAnimated:YES];
	}];
	self.webView = [[DWKWebView alloc] initWithFrame:self.view.bounds];
	[self.view addSubview:self.webView];
#ifdef DEBUG
	[self.webView setDebugMode:YES];
#endif
	[self setUpJSBridge];
}

-(void)setUpJSBridge{
	JSBusSiteBridge *bridge = [[JSBusSiteBridge alloc] init];
	@weakify(self)
	bridge.completeHandler = ^(FilterData *filterData) {
		@strongify(self)
		NSInteger count =  self.filterSearchListBlock(filterData);
		if (count > 1) {
			self.title = [NSString stringWithFormat:@"show %d results",count];
		}else{
			self.title = [NSString stringWithFormat:@"show %d result",count];
		}
	};
	[self.webView addJavascriptObject:bridge namespace:@"busSite"];
	NSString *buldlePath = [[NSBundle mainBundle] bundlePath];
	NSString *basePath = [NSString stringWithFormat:@"%@/dist",buldlePath];
	NSURL *baseUrl = [NSURL fileURLWithPath:basePath isDirectory:YES];
	NSString *indexPath = [NSString stringWithFormat:@"%@/index.html",basePath];
	NSString *htmlContent = [NSString stringWithContentsOfFile:indexPath encoding:NSUTF8StringEncoding error:nil];
	[self.webView loadHTMLString:htmlContent baseURL:baseUrl];

	dispatch_semaphore_t signal = dispatch_semaphore_create(1);
	dispatch_semaphore_wait(signal, dispatch_time(DISPATCH_TIME_NOW, DISPATCH_TIME_FOREVER));
	NSString *jsonString = [self.filterData yy_modelToJSONString];
	dispatch_semaphore_signal(signal);

	if (jsonString) {
		[self.webView callHandler:@"busSite.initFilter" arguments:@[jsonString]];
	}
}


@end
