//  CustomLoadingView
//  JasonDevelop
//
//  Created by Jason Lee on 10/23/14.
//  Copyright (c) jasondevelop. All rights reserved.
//
#import "CommonUtil.h"
#import "CustomLoadingView.h"
#import "ImageUtil.h"

@interface CustomLoadingView () {
    UIView *_bgView, *_containerView;
    UIImageView* _animatedView;
    UIActivityIndicatorView *_indicatorView;
    
    UILabel *_lblMessage;
    UIButton *_btnCancel;
    
    id targetForExecution;
    id objectForExecution;
}

@end

@implementation CustomLoadingView

static CustomLoadingView *__loadingView = nil;

#pragma mark - Singleton

+ (CustomLoadingView *)loadingView {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        CGRect screenRect = [UIScreen mainScreen].bounds;
        __loadingView = [[CustomLoadingView alloc] initWithFrame:screenRect];
    });
    return __loadingView;
}

- (void)showInView:(UIView *)container {
    if ([self superview]) {
        return;
    }
    
    [container addSubview:self];
    [self start];
}

- (void)showInView:(UIView *)container whileExecutingBlock:(dispatch_block_t)block {
    [self showInView:container whileExecutingBlock:block completionHandler:nil];
}

- (void)showInView:(UIView *)container whileExecutingBlock:(dispatch_block_t)block completionHandler:(JDFacadeCompletionCallBackHandler)completion {
    if ([self superview]) {
        return;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.completionBlock = completion;
    
    [container addSubview:self];
    [self start];
    
    dispatch_async(queue, ^(void) {
        block();
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [self cleanUp];
        });
    });
}

- (void)setOperation:(NSOperation *)operation {
    if (!_operation) {
        _operation = operation;
    }
}

- (void)hide {
    if (self) {
        [self stop];
        [self removeFromSuperview];
    }
}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        _bgView = [[UIView alloc] initWithFrame:self.frame];
        _bgView.backgroundColor = [UIColor darkGrayColor];
        _bgView.alpha = 0.35;
        [self addSubview:_bgView];

        
        //container
        CGFloat multiply = IS_IPHONE_6P ? 1.2f : 1.0f;
        
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 140 * multiply, 40 * multiply)];
        _containerView.backgroundColor = RGBCOLOR(46, 141, 205);
//        _containerView.backgroundColor = [UIColor blackColor];
        _containerView.layer.cornerRadius = 20.0f * multiply;
        
        CGFloat oriY = (_containerView.height - 24) / 2;
        //indicator
        CGRect lRect = CGRectMake(oriY, oriY, 24, 24);
        
        _indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:lRect];
        _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        _indicatorView.frame = lRect;
        
        //Label
        _lblMessage = [[UILabel alloc] initWithFrame:CGRectMake(42 * multiply, oriY, 60, 24)];
        _lblMessage.font = [UIFont systemFontOfSize:14.0f];
        _lblMessage.text = @"Loading";
        _lblMessage.textColor = [UIColor whiteColor];
        _lblMessage.textAlignment = NSTextAlignmentCenter;
        
        //button
        _btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnCancel.frame = CGRectMake(108 * multiply, oriY, 24, 24);
        
        UIImage *nimage = [ImageUtil resizeImage:[UIImage imageNamed:@"common_btn_loading_close"] width:24  height:24];
        UIImage *himage = [ImageUtil resizeImage:[UIImage imageNamed:@"common_btn_loading_close_press"] width:24 height:24];
        
        [_btnCancel setImage:nimage forState:UIControlStateNormal];
        [_btnCancel setImage:himage forState:UIControlStateHighlighted];
        
        [_btnCancel addTarget:self action:@selector(btnCancelTouched:) forControlEvents:UIControlEventTouchUpInside];

        CGRect center = [CommonUtil getCenterPosition:_containerView fromContainer:self hasNavigationBar:YES hasTabBar:NO];
        _containerView.frame = center;
        
        [_containerView addSubview:_indicatorView];
        [_containerView addSubview:_lblMessage];
        [_containerView addSubview:_btnCancel];
        
        [self addSubview:_containerView];
    }
    return self;
}



- (void)start {
    [_indicatorView startAnimating];
}

- (void)stop {
    [_indicatorView stopAnimating];
}

- (void)btnCancelTouched:(id)sender {
    if (_operation.isExecuting) {
        [_operation cancel];
    }
    
    [self cleanUp];
}

- (void)cleanUp {
    if (_operation) {
        _operation = nil;
    }
    
    [self stop];
    [self removeFromSuperview];
    
    if (self.completionBlock) {
        self.completionBlock();
        self.completionBlock = NULL;
    }
}

@end
