//
//  CustomAlertView.m
//  JasonDevelop
//
//  Created by Jason Lee on 3/6/14.
//  Copyright (c) jasondevelop. All rights reserved.
//
#import <objc/runtime.h>
#import "NSString-Addtions.h"
#import "CustomAlertView.h"
#import "CustomButton.h"
#import "Masonry.h"
#import "ImageUtil.h"

//#import "AppDelegate.h"

#define kfButtonSize 260.0f
#define kfBoxCap 4.0f
//#define kfTopInset 0
//#define kfRightInset 20
//#define kfBottomInset 0
//#define kfLeftInset 20

static NSString *CustomAlertViewHandlerRunTimeAccosiationKey = @"CustomAlertViewHandlerRunTimeAccosiationKey";

@interface CustomAlertView () {
    
}
@end

@implementation CustomAlertView

//커스텀 얼럿 인스턴스를 생성함, 단순 형태
- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate OKButtonTitle:(NSString *)okButtonTitle cancelButtonTitle:(NSString *)cancelButtonTitle {

    NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"CustomAlertView"
                                                      owner:nil
                                                    options:nil];
    self = (CustomAlertView*)[nibViews firstObject];
    CGRect screenRect = [UIScreen mainScreen].bounds;
    self.frame = screenRect;
    
    //메시지, 버튼 타이틀 설정
    _okButtonTitle = okButtonTitle;
    _cancelButtonTitle = cancelButtonTitle;

    //팝업 이미지 Stretch
    [_imgTitleBar setImage:[UIImage imageNamed:@"img_popup_bg_head"]inset:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    _lblTitle.text = title;
    _lblMessage1.text = message;
    
    [_btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    [_btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [_btnConfirmSingle setBackgroundImage:[UIImage imageNamed:@"img_popup_btn"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    [_btnConfirmSingle setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
    
    [_btnConfirm setTitle:okButtonTitle forState:UIControlStateNormal];
    
    [_btnConfirmSingle setHidden:YES];
    [_btnCancelSingle setHidden:YES];
    [_btnConfirm setHidden:NO];
    [_btnCancel setHidden:NO];
    if (_cancelButtonTitle && ![_cancelButtonTitle isEmptyString]) {

        [_btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
        [_btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
        
        [_btnCancel setTitle:_cancelButtonTitle forState:UIControlStateNormal];
        
        [_btnCancelSingle setBackgroundImage:[UIImage imageNamed:@"img_popup_btn"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
        [_btnCancelSingle setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
        
        [_btnCancelSingle setTitle:_cancelButtonTitle forState:UIControlStateNormal];
    }else{
        [_btnConfirmSingle setHidden:NO];
        [_btnConfirm setHidden:YES];
        [_btnCancel setHidden:YES];
    }
    
    return self;
}

- (void)didMoveToSuperview {
    
    if (!self.superview) {
        return;
    }

    if (!_cancelButtonTitle) {
        if (_btnCancel && [_btnCancel superview]) {
            [_containerView removeConstraint:_constraintBtnSameWidth];
            [_btnCancel removeFromSuperview];
            
            CGFloat constant = 15.0f;
            if (IPHONE_WIDTH == 414.0f) {//아이폰 6p일 경우,
                constant = 15 + 20.0f;
            } else if (IPHONE_WIDTH == 375.0f) {//아이폰 6일경우
                constant = 15 + 12.0f;
            }
            _constraintBtnConfirmWidth.constant = (IPHONE_WIDTH - (constant*2));
            _btnCancel = nil;
        }
    }
}

- (void)hideWithButtonIndex:(NSInteger)index {
    
    [self alertView:self clickedButtonAtIndex:index];
    [self hide];
}

- (IBAction)btnConfirmTouched:(id)sender {

    [self alertView:self clickedButtonAtIndex:0];
    [self hide];
}

- (IBAction)btnConfirmSingleTouched:(id)sender {
    
    [self alertView:self clickedButtonAtIndex:0];
    [self hide];
}

- (IBAction)btnCancelTouched:(id)sender {

    [self alertView:self clickedButtonAtIndex:1];
    [self hide];
}

- (IBAction)btnCancelSingleTouched:(id)sender {
    [self alertView:self clickedButtonAtIndex:1];
    [self hide];
}


- (void)hide {//just hide
    
    [self removeFromSuperview];
    
    UIView *topview = [CommonUtil topView];
    
    for (UIView *subview in [topview.subviews reverseObjectEnumerator]) {
        if ([subview isKindOfClass:[CustomAlertView class]]) {
            
            [UIView animateWithDuration:kfAnimationDur animations:^{
                subview.alpha = 1.0f;
            }];
            break;
        }
    }
}

- (void)show {
    
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
        return;
    }
    
    //얼럿이 뜨는 경우, 로딩창을 종료함.
    UIView *topview = [CommonUtil topView];
    
    if (!topview) {
        [self performSelector:@selector(show) withObject:nil afterDelay:0.3f];
        return;
    }
    
    for (UIView *subview in [topview.subviews reverseObjectEnumerator]) {
        
        if ([subview isKindOfClass:[CustomAlertView class]]) {
            
            [UIView animateWithDuration:kfAnimationDur animations:^{
                subview.alpha = 0.0f;
            }];
            
            break;
        }
    }

    [topview addSubview:self];
    [topview bringSubviewToFront:self];
    
//    NSLog(@"%s\n %@, %zd : 0=active, 1=inactive, 2=background", __PRETTY_FUNCTION__, topView, [UIApplication sharedApplication].applicationState);
}

- (CGSize)sizeForMessage:(CGFloat)margin {
    
    if ([_lblMessage1.text isEqualToString:ksEmptyString]) {
        return CGSizeZero;
    }
    
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize labelSize = (CGSize){IPHONE_WIDTH - (margin * 2) - 40, FLT_MAX};
    CGRect r = [_lblMessage1.text boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:_lblMessage1.font} context:context];
    
    r = CGRectIntegral(r);
    return r.size;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGRect screenRect = [UIScreen mainScreen].bounds;
    self.frame = screenRect;

    if (_maskingView.superview) {    
        [_maskingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(screenRect.size.width);
            make.height.mas_equalTo(screenRect.size.height);
            make.center.equalTo(self);
        }];
    }

    if (_popUpView.superview) {
//        CGFloat constant = 15.0f;
//        if (IPHONE_WIDTH == 414.0f) {//아이폰 6p일 경우,
//            constant = 15 + 20.0f;
//        } else if (IPHONE_WIDTH == 375.0f) {//아이폰 6일경우
//            constant = 15 + 12.0f;
//        }
//        
//        CGFloat adjustHeight = 0.0f;
//        if ([self isMemberOfClass:[CustomAlertView class]]) {
//            CGFloat height = [self sizeForMessage:constant].height;
//            adjustHeight = height > 17 ? height - 17 : 0;
//            
//            _constraintPopupHeight.constant = 199 + adjustHeight;
//        }

//        CGFloat pheight = _constraintPopupHeight ? _constraintPopupHeight.constant : _popUpView.frame.size.height;
        
        [_popUpView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.leading.equalTo(_maskingView).offset(constant);    //remove at build time
//            make.trailing.equalTo(_maskingView).offset(-constant);
            
            CGFloat margin = ceil(screenRect.size.height - _popUpView.frame.size.height) / 2;
            make.top.mas_equalTo(margin);
            make.bottom.mas_equalTo(-margin);
        }];

        
        [self layoutIfNeeded];
    }
}


- (void)showWithCompletion:(CustomAlertViewCallBackHandler)completion {

    //set runtime accosiation of object
    //param -  sourse object for association, association key, association value, policy of association
    objc_setAssociatedObject(self, (__bridge const void *)(CustomAlertViewHandlerRunTimeAccosiationKey), completion, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//    objc_setAssociatedObject(self, (__bridge const void *)(CustomAlertViewHandlerRunTimeAccosiationKey), completion, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self show];
}

- (void)alertView:(CustomAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    CustomAlertViewCallBackHandler completionHandler = objc_getAssociatedObject(self, (__bridge  const void *)(CustomAlertViewHandlerRunTimeAccosiationKey));
    if (completionHandler != nil) {
        completionHandler(alertView, buttonIndex);
    }
}

- (void)alertView:(CustomAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

    CustomAlertViewCallBackHandler completionHandler = objc_getAssociatedObject(self, (__bridge  const void *)(CustomAlertViewHandlerRunTimeAccosiationKey));
    if (completionHandler != nil) {
        completionHandler(alertView, buttonIndex);
    }
}

@end
