//
//  BFActivityView.m
//  LIDONG
//
//  Created by LiDong on 13-7-12.
//  Copyright (c) 2013年 LIDONG. All rights reserved.
//

#import "BFActivityView.h"
#import <QuartzCore/QuartzCore.h>
#import <sys/time.h>

#define kMinDisplayTimeInterval 1.f

@interface BFActivityView () {
    UIWindow *mWindow;
    UIView *mContentView;
    UIActivityIndicatorView *mActivityIndicatorView;
    UILabel *mTextLabel;
    id<BFActivityViewDelegate> __weak mDelegate;
    NSTimeInterval mAppearedTimestamp;
    BOOL mHidesBackground;
}

@end

@implementation BFActivityView

@synthesize delegate = mDelegate;
@synthesize hidesBackground = mHidesBackground;

- (id)init {
    if (self = [super initWithFrame:CGRectZero]) {
        UIColor *clearColor = [UIColor clearColor];
        UIColor *whiteColor = [UIColor whiteColor];
        
        [self setBackgroundColor:clearColor];
        [self setExclusiveTouch:NO];
        
        mContentView = [[UIView alloc] initWithFrame:CGRectZero];
        [mContentView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.65]];
        
        CALayer *layer = [mContentView layer];
        
        [layer setMasksToBounds:NO];
        [layer setCornerRadius:5];
        [layer setBorderWidth:0.5f];
        [layer setBorderColor:[whiteColor CGColor]];
        [layer setShadowColor:[[UIColor blackColor] CGColor]];
        [layer setShadowOpacity:1];
        [layer setShadowOffset:CGSizeZero];
        
        [self addSubview:mContentView];
        
        mActivityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [mActivityIndicatorView setHidesWhenStopped:YES];
        [mActivityIndicatorView setCenter:CGPointMake(160, 220)];
        [self addSubview:mActivityIndicatorView];
        
        mTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 240, 200, 20)];
        [mTextLabel setBackgroundColor:clearColor];
        [mTextLabel setTextColor:whiteColor];
        [mTextLabel setTextAlignment:NSTextAlignmentCenter];
        [mTextLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [mTextLabel setNumberOfLines:0];
        [self addSubview:mTextLabel];
    }
    return self;
}

//- (void)dealloc {
//    [mContentView release];
//    [mActivityIndicatorView release];
//    [mTextLabel release];
//    [mWindow release];
//    
//    [super dealloc];
//}

- (void)calculateLayoutForBounds:(const CGRect)bounds title:(NSString *)title {
    BOOL isAnimating = [mActivityIndicatorView isAnimating];
    BOOL hasTitle = (title && ![title isEqualToString:NSStringEmpty]) ? YES : NO;
    CGSize contentSize = { 80, 60 };
    
    if (hasTitle) {
        [mTextLabel setNumberOfLines:1];
        [mTextLabel sizeToFit];
        
//        UIFont *font = [mTextLabel font];
        CGRect textFrame = CGRectZero;
        
//        textFrame.size = [title sizeWithFont:font];
        
        if (textFrame.size.width > 240.f) {
//            const CGSize constrainedSize = { 240, CGFLOAT_MAX };
            
//            textFrame.size = [title sizeWithFont:font constrainedToSize:constrainedSize lineBreakMode:NSLineBreakByWordWrapping];
        }
        
        contentSize.height = textFrame.size.height + (isAnimating ? 67 : 40);
        
        const CGFloat newContentWidth = textFrame.size.width + 40;
        
        contentSize.width = (newContentWidth > contentSize.width) ? newContentWidth : contentSize.width;
        textFrame.origin.x = (bounds.size.width - textFrame.size.width) / 2;
        
        if (isAnimating) {
            textFrame.origin.y = bounds.size.height / 2 + 15;
        } else {
            textFrame.origin.y = (bounds.size.height - textFrame.size.height) / 2;
        }
        [mTextLabel setFrame:textFrame];
    }
    
    const CGRect contentFrame = { (bounds.size.width - contentSize.width) / 2, (bounds.size.height - contentSize.height) / 2, contentSize.width, contentSize.height };
    
    [mContentView setFrame:contentFrame];
    
    if (isAnimating) {
        const CGPoint indicatorCenter = { bounds.size.width / 2.f, contentFrame.origin.y + (hasTitle ? 28 : (contentSize.height / 2.f)) };
        
        [mActivityIndicatorView setCenter:indicatorCenter];
    }
}

- (void)showWithTitle:(NSString *)title {
    struct timeval tv = { 0 };
    
    gettimeofday(&tv, 0);
    mAppearedTimestamp = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.f;
    
    if (nil == mWindow) {
        mWindow = [[UIWindow alloc] initWithFrame:FWScreenBounds];
        
        [mWindow setBackgroundColor:[UIColor clearColor]];
        [mWindow setWindowLevel:UIWindowLevelStatusBar];
    }
    
    [self setAlpha:0];
    [self setFrame:FWScreenBounds];
    [mActivityIndicatorView startAnimating];
    [mTextLabel setText:title];
    [self calculateLayoutForBounds:FWScreenBounds title:title];
    [self setExclusiveTouch:NO];
    [self setUserInteractionEnabled:YES];
    [mWindow addSubview:self];
    [mWindow setHidden:NO];
    
    [UIView animateWithDuration:0.25 animations:^{
        [self setAlpha:1];
    } completion:^(BOOL finished){
    }];
}

- (NSTimeInterval)delayTimeInterval {
    struct timeval tv = { 0 };
    
    gettimeofday(&tv, 0);
    const NSTimeInterval currentTime = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.f;
    const NSTimeInterval interval = currentTime - mAppearedTimestamp;
    NSTimeInterval delay = 0.f;
    
    if (0.f <= interval && interval < kMinDisplayTimeInterval) {
        delay = kMinDisplayTimeInterval - interval;
    }
    DLog(@"delay: %f", delay);
    return delay;
}

- (void)dismiss {
    [UIView animateWithDuration:0.25 delay:[self delayTimeInterval] options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self setAlpha:0];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)dismissWithTitle:(NSString *)title {
    [mActivityIndicatorView stopAnimating];
    [mTextLabel setText:title];
    [self calculateLayoutForBounds:FWScreenBounds title:title];
    [self setExclusiveTouch:NO];
    [self setUserInteractionEnabled:NO];
    
    [UIView animateWithDuration:0.25 delay:[self delayTimeInterval] options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self setAlpha:0];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)detachDelegate:(id)aDelegate {
    if (aDelegate == mDelegate) {
        mDelegate = nil;
    }
}

- (void)didMoveToSuperview {
    if (nil == [self superview]) {
        [mWindow setHidden:YES];
        [mDelegate activityViewDidDismiss:self];
    }
}

- (void)setHidesBackground:(BOOL)hidesBackground {
    mHidesBackground = hidesBackground;
    [mContentView setHidden:mHidesBackground];
}

@end
