//
//  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 "Masonry.h"

//#import "AppDelegate.h"

#define kfButtonSize 260.0f
#define kfBoxCap 4.0f

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;
    _lblBoldMessage.hidden = YES;
    _lblMessage2.hidden = YES;

    CGRect m1Rect = _lblMessage1.frame;

    _lblTitle.text = title;

    //텍스트 사이즈 만큼 레이블사이즈를 늘림
    _lblMessage1.text = message;
    m1Rect.size.height = [CommonUtil getLabelRealHeight:_lblMessage1];
    _lblMessage1.frame = m1Rect;
    
    [_btnConfirm setTitle:okButtonTitle forState:UIControlStateNormal];
    
    if (_cancelButtonTitle && ![_cancelButtonTitle isEmptyString]) {
        [_btnCancel setTitle:_cancelButtonTitle forState:UIControlStateNormal];
    }
    
    return self;
}

//커스텀 얼럿 인스턴스를 생성함, 볼드메시지와 메시지1, 메시지2를 가지고 있음.
- (id)initWithTitle:(NSString *)title delegate:(id)delegate OKButtonTitle:(NSString *)okButtonTitle cancelButtonTitle:(NSString *)cancelButtonTitle message:(NSString *)messages,... {

    NSString *boldMessage = messages;
    NSString *message1 = nil, *message2 = nil;

    va_list args;
    va_start(args, messages);

    NSInteger i = 0;
    while ((messages = va_arg(args, id)) != nil) {//루프 - 입력된 메시지를 받아옴.
        if (i == 0) {
            message1 = messages;
        } else if (i == 1) {
            message2 = messages;
        }
        i++;
    }

    va_end(args);

    self = [self initWithTitle:title message:message1 delegate:delegate OKButtonTitle:okButtonTitle cancelButtonTitle:cancelButtonTitle];

    _lblBoldMessage.hidden = [boldMessage isEmptyString];
    _lblMessage2.hidden = [message2 isEmptyString];


    CGRect m1Rect = _lblMessage1.frame;

    if (!_lblBoldMessage.hidden) {//볼드 메시지가 있을 경우,

        _lblBoldMessage.text = boldMessage;
        [_lblBoldMessage sizeToFit];
        [CommonUtil moveToCenterHorizon:_lblBoldMessage withContainer:_popUpView];
        CGRect bRect = _lblBoldMessage.frame;
        bRect.origin.y = m1Rect.origin.y;
        _lblBoldMessage.frame = bRect;

        m1Rect.origin.y = bRect.origin.y + bRect.size.height + kfLabelMargin;
        _lblMessage1.frame = m1Rect;
    }

    if (!_lblMessage2.hidden) {//2번 메시지가 있을 경우,

        _lblMessage2.text = message2;
        [_lblMessage2 sizeToFit];
        [CommonUtil moveToCenterHorizon:_lblMessage2 withContainer:_popUpView];
        CGRect m2Rect = _lblMessage2.frame;
        m2Rect.origin.y = m1Rect.origin.y + m1Rect.size.height + kfLabelMargin;
        _lblMessage2.frame = m2Rect;
    }

    return self;
}


- (void)didMoveToSuperview {

    if (!_cancelButtonTitle) {
        if (_btnCancel && [_btnCancel superview]) {
            [_containerView removeConstraint:_constraintBtnSameWidth];
            [_btnCancel removeFromSuperview];
            _constraintBtnConfirmWidth.constant = (IPHONE_WIDTH - 30);
            _btnCancel = nil;
        }
    }
}

- (IBAction)btnConfirmTouched:(id)sender {

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

- (IBAction)btnCancelTouched:(id)sender {

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

- (void)show {
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
        return;
    }
    
    //얼럿이 뜨는 경우, 로딩창을 종료함.
    UIView *topView = [CommonUtil topView];
    if (!topView) {
        [self performSelector:@selector(show) withObject:nil afterDelay:0.3f];
        return;
    }

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

- (void)layoutSubviews {
    [super layoutSubviews];

    
    if (IOS_VERSION >= 8.0) {
        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) {
            [_popUpView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_maskingView).offset(15);
                make.right.equalTo(_maskingView).offset(-15);
                
                CGFloat margin = ceil(screenRect.size.height - _popUpView.frame.size.height) / 2;
                make.top.mas_equalTo(margin);
                make.bottom.mas_equalTo(-margin);
            }];
        }
    }
}


- (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
