//
//  iToast.m
//  iToast
//
//  Created by Diallo Mamadou Bobo on 2/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "iToast.h"
#import <QuartzCore/QuartzCore.h>

static iToastSettings *sharedSettings = nil;

@interface iToast(private)

- (iToast *) settings;

@end


@implementation iToast

- (id)initWithText:(NSString *)_text {
	if (self = [super init]) {
		text = [_text copy];
	}
    useAttr = NO;
	return self;
}

- (id)initWithAttrText:(NSAttributedString *)_text {
    if (self = [super init]) {
        attartext = [_text copy];
    }
    useAttr = YES;
    return self;
}

- (void)show {
	iToastSettings *theSettings = _settings;
	
	if (!theSettings) {
		theSettings = [iToastSettings getSharedSettings];
	}
    
    if (useAttr)
    {
        text = [attartext string];
    }
    
    CGFloat titleSize = 16.f;
    CGSize textSize = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width * 0.75, 100)
                                         options:(NSStringDrawingUsesLineFragmentOrigin)
                                      attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:titleSize], NSForegroundColorAttributeName:[UIColor whiteColor]}
                                         context:nil].size;
	
	//UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, textSize.width + 20, textSize.height + 20)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, textSize.width + 2.f, (textSize.height + 20) > 50 ? (textSize.height + 20) : 50)];
	label.backgroundColor = [UIColor clearColor];
    label.textAlignment = NSTextAlignmentCenter;
	label.textColor = [UIColor whiteColor];
	label.font = [UIFont systemFontOfSize:titleSize];
    
    if ((useAttr))
    {
        [label setAttributedText:attartext];
    }
    else
    {
        label.text = text;
    }
    
	label.numberOfLines = 0;
	label.shadowColor = [UIColor darkGrayColor];
	label.shadowOffset = CGSizeMake(1, 1);
	
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, textSize.width + 20 + 2.f, (textSize.height + 20) > 50 ? (textSize.height + 20) : 50);
	label.center = CGPointMake(button.frame.size.width / 2, button.frame.size.height / 2);
	[button addSubview:label];
    [label release];
	button.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
//    button.backgroundColor = HWHUDColor;
	button.layer.cornerRadius = 5;
	button.center = CGPointMake([self getScreenSize].width/2, [self getScreenSize].height/2);
    
	NSTimer *timer = [NSTimer timerWithTimeInterval:((float)theSettings.duration)/1000 target:self selector:@selector(hideToast:) userInfo:nil repeats:NO];
	[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    UIViewController *vc = [self appRootViewController];
    if ([vc isKindOfClass:[UIAlertController class]])
    {
        button.center = CGPointMake(vc.view.frame.size.width/2, vc.view.frame.size.height/2);
    }
    
    [vc.view addSubview:button];
    
	view = [button retain];
	[button addTarget:self action:@selector(hideToast:) forControlEvents:UIControlEventTouchDown];
}

- (void)hideToast:(NSTimer *)theTimer {
	[UIView beginAnimations:nil context:NULL];
    [view removeFromSuperview];
	[UIView commitAnimations];
	NSTimer *timer = [NSTimer timerWithTimeInterval:500 target:self selector:@selector(hideToast:) userInfo:nil repeats:NO];
	[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)removeToast:(NSTimer *)theTimer {
	[view removeFromSuperview];
}

+ (iToast *)makeText:(NSString *)_text {
	iToast *toast = [[[iToast alloc] initWithText:_text] autorelease];
	return toast;
}

+ (iToast *)makeAttrText:(NSAttributedString *)_attrtext {
    iToast *toast = [[[iToast alloc] initWithAttrText:_attrtext] autorelease];
    return toast;
}

- (iToast *)setDuration:(NSInteger)duration {
	[self theSettings].duration = duration;
	return self;
}

- (iToast *)setGravity:(iToastGravity)gravity offsetLeft:(NSInteger) left offsetTop:(NSInteger)top {
	[self theSettings].gravity = gravity;
	offsetLeft = left;
	offsetTop = top;
	return self;
}

- (iToast *)setGravity:(iToastGravity)gravity {
	[self theSettings].gravity = gravity;
	return self;
}

- (iToast *)setPostion:(CGPoint)_position {
	[self theSettings].postition = CGPointMake(_position.x, _position.y);
	return self;
}

- (iToastSettings *)theSettings {
	if (!_settings) {
		_settings = [[iToastSettings getSharedSettings] copy];
	}
	return _settings;
}

- (CGSize)getScreenSize {
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    if ((NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return CGSizeMake(screenSize.height, screenSize.width);
    }
    return screenSize;
}

- (UIViewController *)appRootViewController {
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

@end


@implementation iToastSettings
@synthesize duration;
@synthesize gravity;
@synthesize postition;
@synthesize images;

- (void)setImage:(UIImage *)img forType:(iToastType)type{
	if (!images) {
		images = [[NSMutableDictionary alloc] initWithCapacity:4];
	}
	
	if (img) {
		NSString *key = [NSString stringWithFormat:@"%i", type];
		[images setValue:img forKey:key];
	}
}

+ (iToastSettings *)getSharedSettings{
	if (!sharedSettings) {
		sharedSettings = [iToastSettings new];
		sharedSettings.gravity = iToastGravityCenter;
		sharedSettings.duration = iToastDurationNormal;
	}
	
	return sharedSettings;
	
}

- (id)copyWithZone:(NSZone *)zone{
	iToastSettings *copy = [iToastSettings new];
	copy.gravity = self.gravity;
	copy.duration = self.duration;
	copy.postition = self.postition;
	
	NSArray *keys = [self.images allKeys];
	
	for (NSString *key in keys){
		[copy setImage:[images valueForKey:key] forType:[key intValue]];
	}
	
	return copy;
}

@end
