//
//  PhotoZoomImageViewController.m
//  Images
//
//  Created by Hagbarðr on 4/18/19.
//

#import "PhotoZoomImageViewController.h"

@interface PhotoZoomImageViewController () <UIScrollViewDelegate> {
	NSURL *_imageURL;
	BOOL _didFinishAppearance;
	UIImage *_loadedImageForDelayedAppearance;
}

@property (nonatomic, weak) IBOutlet UIScrollView *scrollView;
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UIActivityIndicatorView *wheel;

- (void)setImageURL:(NSURL*)imageURL;

@end

@implementation PhotoZoomImageViewController

+ (PhotoZoomImageViewController*)instantiateWithImage:(UIImage*)image {
	PhotoZoomImageViewController *vc = [[PhotoZoomImageViewController alloc] initWithNibName:@"PhotoZoomImageViewController" bundle:nil];
	[vc.imageView setImage:image];
	return vc;
}

+ (PhotoZoomImageViewController*)instantiateWithImageURL:(NSURL*)imageURL {
	PhotoZoomImageViewController *vc = [[PhotoZoomImageViewController alloc] initWithNibName:@"PhotoZoomImageViewController" bundle:nil];
	[vc setImageURL:imageURL];
	return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	[self.view setBackgroundColor:UIColor.clearColor];
	UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(autoZoom:)];
	[doubleTap setNumberOfTapsRequired:2];
	[self.scrollView addGestureRecognizer:doubleTap];
}

- (void)autoZoom:(UITapGestureRecognizer*)gestureRecognizer {
	if(self.scrollView.zoomScale > self.scrollView.minimumZoomScale) {
		[self.scrollView setZoomScale:self.scrollView.minimumZoomScale animated:true];
	} else {
		[self.scrollView setZoomScale:self.scrollView.maximumZoomScale animated:true];
	}
}

- (void)viewWillAppear:(BOOL)animated {
	_didFinishAppearance = false;
	[super viewWillAppear:animated];
	[self loadImageIfNeeded];
}

- (void)viewDidAppear:(BOOL)animated {
	_didFinishAppearance = true;
	[super viewDidAppear:animated];
	if(_loadedImageForDelayedAppearance != nil) {
		self.imageView.image = _loadedImageForDelayedAppearance;
		_loadedImageForDelayedAppearance = nil;
	}
}

- (void)setImageURL:(NSURL*)imageURL {
	_imageURL = imageURL;
	if(_didFinishAppearance) {
		[self loadImageIfNeeded];
	}
}

- (void)loadImageIfNeeded {
	//[self.scrollView zoomToRect:self.view.bounds]; // FIXME
	if(_imageURL != nil && self.imageView.image == nil) {
		_loadedImageForDelayedAppearance = nil;
		[self.wheel startAnimating];
		[[[NSURLSession sharedSession] dataTaskWithURL:_imageURL
									 completionHandler:^(NSData *data,
														 NSURLResponse *response,
														 NSError *error) {
										 if (error || !data.length) {
											 //NSLog(@"ERROR loading image %@",_imageURL);
											 return;
										 } else {
											 CGFloat sizeInMB = (CGFloat)(data.length/1024.0f/1024.0f);
											 //NSLog(@"File size is : %.2f MB",sizeInMB);
											 // delay appearance to avoid stuttering on slower devices:
											 BOOL delayAppearance = (sizeInMB > 5);
											 UIImage *image = [UIImage imageWithData:data];
											 if(delayAppearance && !_didFinishAppearance) {
												 _loadedImageForDelayedAppearance = image;
											 } else {
												 dispatch_async(dispatch_get_main_queue(), ^{
													 self.imageView.image = image;
												 });
											 }
										 }
										 dispatch_async(dispatch_get_main_queue(), ^{
											 [self.wheel stopAnimating];
										 });
									 }] resume];
		
	}
}

#pragma mark - UIScrollViewDelegate

- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
	return self.imageView;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view {
	
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view atScale:(CGFloat)scale {
	
}

@end
