//
//  DSToast.m
//  DSToast
//
//  Created by LS on 8/18/15.
//  Copyright (c) 2015 LS. All rights reserved.
//

#import "DSToast.h"
#import "SDGeneralDefine.h"
#import "UIViewExt.h"

@interface DSToast ()<CAAnimationDelegate>

@end

static CFTimeInterval const kDefaultForwardAnimationDuration = 0.5;
static CFTimeInterval const kDefaultBackwardAnimationDuration = 0.5;
static CFTimeInterval const kDefaultWaitAnimationDuration = 1.0;

static CGFloat const kDefaultTopMargin = 50.0;
static CGFloat const kDefaultBottomMargin = 50.0;
//static CGFloat const kDefalultTextInset = 10.0;

@implementation DSToast

+ (id)toastWithText:(NSString *)text
{
    DSToast *toast = [[DSToast alloc] initWithText:text];
    
    return toast;
}

- (id)initWithText:(NSString *)text
{
    self = [self initWithFrame:CGRectZero];
    if(self)
    {
        self.text = text;
        [self sizeToFit];
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        self.forwardAnimationDuration = kDefaultForwardAnimationDuration;
        self.backwardAnimationDuration = kDefaultBackwardAnimationDuration;
        self.textInsets = UIEdgeInsetsMake(13.5, 44, 13.5, 44);
        self.maxWidth = CGRectGetWidth([[UIScreen mainScreen] bounds]) - 20.0;
        self.layer.cornerRadius = 6.0;
        self.layer.masksToBounds = YES;
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        self.numberOfLines = 0;
        self.textAlignment = NSTextAlignmentLeft;
        self.textColor = [UIColor whiteColor];
        self.font = KFontNameMediumSize(13.0);
        self.toastShowType = DSToastShowTypeCenter;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    }
    
    return self;
}
- (void)changeRotate:(NSNotification*)noti{
    [self endEditing:YES];
    
    if (self.toastShowType == DSToastShowTypeCenter) {
        self.center = KFirstWindow.center;
    }else{
        self.centerX = KFirstWindow.centerX;
        self.centerY = KFirstWindow.centerY-100;
    }
}

#pragma mark - Show Method

- (void)showInView:(UIView *)view
{
    [self addAnimationGroup];
    CGPoint point = view.center;
    point.y = CGRectGetHeight(view.bounds)- kDefaultBottomMargin;
    self.center = point;
    for (int i=0; i<view.subviews.count; i++) {
        if (i == view.subviews.count-1) {
            if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
                [view.subviews[i] removeFromSuperview];
                [view addSubview:self];
            }else{
                [view addSubview:self];
            }
        }else{
            if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
                [view.subviews[i] removeFromSuperview];
            }
        }
    }
}

- (void)showInView:(UIView *)view showType:(DSToastShowType)type
{
    self.toastShowType = type;
    
    [self addAnimationGroup];
    CGPoint point = view.center;
    switch (type) {
        case DSToastShowTypeTop:
            
            point.y = kDefaultTopMargin;
            break;
    
        case DSToastShowTypeBottom:
            
            point.y = CGRectGetHeight(view.bounds)- kDefaultBottomMargin;
            break;
            
        default:
            break;
    }
    
    self.center = point;
    self.layer.cornerRadius = self.frame.size.height/2;
    self.layer.masksToBounds = YES;
    for (int i=0; i<view.subviews.count; i++) {
        if (i == view.subviews.count-1) {
            if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
                [view.subviews[i] removeFromSuperview];
                [view addSubview:self];
            }else{
                [view addSubview:self];
            }
        }else{
            if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
                [view.subviews[i] removeFromSuperview];
            }
        }
    }
}
-(void)layoutSubviews{
    [super layoutSubviews];
    
    if (self.toastShowType == DSToastShowTypeCenter) {
        self.center = KFirstWindow.center;
    }else{
        self.centerX = KFirstWindow.centerX;
        self.centerY = KFirstWindow.centerY-100;
    }
}
#pragma mark - Animation

- (void)addAnimationGroup
{
    CABasicAnimation *forwardAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    forwardAnimation.duration = self.forwardAnimationDuration;
    forwardAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.5f :1.7f :0.6f :0.85f];
    forwardAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    forwardAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    
    CABasicAnimation *backwardAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    backwardAnimation.duration = self.backwardAnimationDuration;
    backwardAnimation.beginTime = forwardAnimation.duration + kDefaultWaitAnimationDuration;
    backwardAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.4f :0.15f :0.5f :-0.7f];
    backwardAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
    backwardAnimation.toValue = [NSNumber numberWithFloat:0.0f];
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = @[forwardAnimation,backwardAnimation];
    animationGroup.duration = forwardAnimation.duration + backwardAnimation.duration + kDefaultWaitAnimationDuration;
    animationGroup.removedOnCompletion = NO;
    animationGroup.delegate = self;
    animationGroup.fillMode = kCAFillModeForwards;
    
    [self.layer addAnimation:animationGroup forKey:nil];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if(flag)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [self removeFromSuperview];
    }
}

- (void)setTextInsets:(UIEdgeInsets)textInsets{
    CGRect frame = self.frame;
    CGFloat width = CGRectGetWidth(self.bounds) + textInsets.left + textInsets.right;
    
    frame.size.width = width > self.maxWidth? self.maxWidth : width;
    frame.size.height = CGRectGetHeight(self.bounds) + textInsets.top + textInsets.bottom;
    self.frame = frame;
    self.textAlignment = NSTextAlignmentCenter;

}

#pragma mark - Text Configurate

- (void)sizeToFit
{
    [super sizeToFit];
    
    CGRect frame = self.frame;
    CGFloat width = CGRectGetWidth(self.bounds) + self.textInsets.left + self.textInsets.right;
    
    frame.size.width = width > self.maxWidth? self.maxWidth : width;
    frame.size.height = CGRectGetHeight(self.bounds) + self.textInsets.top + self.textInsets.bottom;
    self.frame = frame;
}

- (void)drawTextInRect:(CGRect)rect
{
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.textInsets)];
}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
   bounds.size = [self.text boundingRectWithSize:CGSizeMake(self.maxWidth - self.textInsets.left - self.textInsets.right,
                                               CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;
    
    return bounds;
}

@end
