//
//  PhotoViewController.m
//  PDFReader
//
//  Created by Dong Li on 12-4-30.
//  Copyright (c) 2013年 ITX. All rights reserved.
//

#import "PhotoViewController.h"
#import "GIFDecoder.h"
#import "FSFileItem.h"

@implementation PhotoViewController

- (id)initWithFileItem:(FSFileItem *)fileItem {
    if (self = [super init]) {
        _fileItem = fileItem;
        
        [self setTitle:[_fileItem displayName]];
        
        _statusBarStyle = UIStatusBarStyleLightContent;
        
        UIBarButtonItem *stopItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(onClose)];
        
        [[self navigationItem] setLeftBarButtonItem:stopItem];
        _actionItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bar/action.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onAction)];
        [_actionItem setEnabled:NO];
        
        UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
        NSArray *toolbarItems = [[NSArray alloc] initWithObjects:_actionItem, flexibleItem, _rotationItem, nil];
        
        [self setToolbarItems:toolbarItems];
        
        _fileQueue = dispatch_queue_create("com.kingfont.photo", 0);
    }
    return self;
}

- (void)loadView {
    _photoView = [[PhotoScrollView alloc] initWithFrame:CGRectPortraitScreen];
    [_photoView setZoomViewDelegate:self];
    
    [self setView:_photoView];
}

UIActivityIndicatorView *UIActivityIndicatorViewCreateInBounds(const CGRect bounds) {
    const CGPoint center = { bounds.origin.x + bounds.size.width / 2.f, bounds.origin.y + bounds.size.height / 2.f };
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    [activityIndicatorView setHidesWhenStopped:YES];
    [activityIndicatorView setCenter:center];
    [activityIndicatorView setAutoresizingMask:UIFlxAllMargins];
    
    return activityIndicatorView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIActivityIndicatorView *activityIndicatorView = UIActivityIndicatorViewCreateInBounds(CGRectPortraitScreen);
    [_photoView addSubview:activityIndicatorView];
    
    [activityIndicatorView startAnimating];
    
    NSString *path = [_fileItem path];
    
    dispatch_async(_fileQueue, ^{
        @autoreleasepool {
            NSString *pathExtension = [[path pathExtension] lowercaseString];
            const dispatch_queue_t mainQueue = dispatch_get_main_queue();
            
            if ([pathExtension isEqualToString:@"gif"]) {
                NSTimeInterval duration = 0;
                NSArray *images = [GIFDecoder decodeFile:path duration:&duration];
                
                dispatch_sync(mainQueue, ^{
                    if ([images count] > 0) {
                        [_photoView setImages:images duration:duration];
                        [_actionItem setEnabled:YES];
                    } else {
                        UIAlert(LS(@"BAD_IMAGE_TITLE"), LS(@"BAD_IMAGE_PROMPT"));
                    }
                });
            } else {
                UIImage *image = [UIImage imageWithContentsOfFile:path];
                
                dispatch_sync(mainQueue, ^{
                    if (image) {
                        [_photoView setImage:image];
                        [_actionItem setEnabled:YES];
                    } else {
                        UIAlert(LS(@"BAD_IMAGE_TITLE"), LS(@"BAD_IMAGE_PROMPT"));
                    }
                });
            }
            dispatch_async(mainQueue, ^{
                [activityIndicatorView stopAnimating];
                [activityIndicatorView removeFromSuperview];
                });
        }
    });
}

- (void)releaseSubviews {
    _photoView = nil;
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIPrintInteractionController sharedPrintController] dismissAnimated:animated];
}

#pragma mark - IFZoomViewDelegate

- (void)toggleFullScreen:(IFZoomView *)zoomView {
    [self reverseFullScreen];
}

#pragma mark - Action

- (void)onAction {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:LS(@"CANCEL") destructiveButtonTitle:nil otherButtonTitles:LS(@"SAVE_TO_PHOTO_LIBRARY"), LS(@"PRINT"), nil];
    
    [actionSheet showInView:[[self navigationController] view]];
}

- (void)onClose {
    [[self navigationController] dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) {
        UIImage *image = [_photoView image];
        
        if (image) {
            UIActivityIndicatorView *activityIndicatorView = UIActivityIndicatorViewCreateInBounds([_photoView bounds]);
            [_photoView addSubview:activityIndicatorView];
            
            [activityIndicatorView startAnimating];
            
            dispatch_async(_fileQueue, ^{
                @autoreleasepool {
                    UIImageWriteToSavedPhotosAlbum(image, nil, NULL, NULL);
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [activityIndicatorView stopAnimating];
                        [activityIndicatorView removeFromSuperview];
                        });
                }
            });
        }
    } else if (1 == buttonIndex) {
        NSURL *URL = [[NSURL alloc] initFileURLWithPath:[_fileItem path]];
        
        if ([UIPrintInteractionController canPrintURL:URL]) {
            UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];
            
            [printController setShowsPageRange:YES];
            [printController setPrintingItem:URL];
            [printController presentAnimated:YES completionHandler:^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error){
            }];
        } else {
            UIAlert(LS(@"CANNOT_PRINT_TITLE"), LS(@"CANNOT_PRINT_PROMPT"));
        }
        }
}

@end
