//
// TourSearchDetailSummaryCell.m
// IvyMedia
//
// Created by paul on 9/11/14.
//
//

#import "TourSearchDetailSummaryCell.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "UIConstants.h"
#import "UniversalViewWrapper.h"
#import <PureLayout/PureLayout.h>

@interface TourSearchDetailSummaryCell () <WKNavigationDelegate> {
	NSUInteger _restorationHash;
}
@property (weak, nonatomic) IBOutlet  UniversalViewWrapper<WKWebView *> *webViewWrapper;
@property (nonatomic, weak) IBOutlet UIActivityIndicatorView *indicatorView;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *heightConstraint;

@property (nonatomic, copy) void (^didFinishLoadBlock) (CGSize contentSize);

@property (nonatomic, strong, readonly) WKWebView *webView;

@end

@implementation TourSearchDetailSummaryCell

- (void)awakeFromNib {
	[super awakeFromNib];
	// Initialization code
	self.webViewWrapper.viewClassName = NSStringFromClass([WKWebView class]);
	
	_restorationHash = -1;
	self.webView.navigationDelegate = self;
	self.webView.scrollView.scrollEnabled = NO;
	[self.indicatorView startAnimating];

	[CocoaUtils fillSeparatorOfCell:self];
}

#pragma mark - Property

- (WKWebView *)webView {
	return [self.webViewWrapper get];
}

#pragma mark - Public

- (void)setHTMLString:(NSString *)html didFinishLoad:(void (^)(CGSize contentSize))block {
	if (self.webView.loading) {
		return;
	}
	NSUInteger newHash = html.hash;
	if (_restorationHash != newHash) {
		_restorationHash = newHash;
		self.didFinishLoadBlock = block;
		[self.webView loadHTMLString:html baseURL:nil];
	}
}

#pragma mark - Web view delegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
	[webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(NSNumber *result, NSError *error) {
		self.heightConstraint.constant = result.floatValue + self.additionalPaddingAtBottom;
		[self.indicatorView stopAnimating];
		if (self.didFinishLoadBlock) {
			self.didFinishLoadBlock([self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]);
		}
	}];
}

@end
