//
//  CustomLabel.m
//  JasonDevelop
//
// Created by Jason Lee on 2013. 12. 10..
//  Copyright (c) jasondevelop. All rights reserved.
//
#import "NSString-Addtions.h"
#import "UIView+AutoLayoutDebugging.h"
#import "CustomLabel.h"
#import "CommonUtil.h"

#define kfBoxCap 4.0f

#define ksEmptyString @""
#define ksSpaceString @""

@interface CustomLabel () {
    id _userInteractionTarget;
    SEL _userInteractionSelector;
    UIEdgeInsets _bgInsets;
    BOOL _isBold;
}

@end

@implementation CustomLabel


//5.1 이전
//애플고딕
//5.1 이상
//애플 산돌 고딕 네오체 (AppleSDGothicNeo)

//Font Family: AppleGothic
//Font: AppleGothic

//iOS 7
//Family name: Apple SD Gothic Neo
//Font name: AppleSDGothicNeo-Thin
//Font name: AppleSDGothicNeo-SemiBold
//Font name: AppleSDGothicNeo-Medium
//Font name: AppleSDGothicNeo-Regular
//Font name: AppleSDGothicNeo-Bold
//Font name: AppleSDGothicNeo-Light

//iOS 6
//Family name: Apple SD Gothic Neo
//Font name: AppleSDGothicNeo-Bold
//Font name: AppleSDGothicNeo-Medium

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        //        self.lineBreakMode = NSLineBreakByCharWrapping;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

//NSString *const NSFontAttributeName;
//NSString *const NSParagraphStyleAttributeName;
//NSString *const NSForegroundColorAttributeName;
//NSString *const NSBackgroundColorAttributeName;
//NSString *const NSLigatureAttributeName;
//NSString *const NSBaselineOffsetAttributeName;
//NSString *const NSStrikethroughStyleAttributeName;
//NSString *const NSStrokeColorAttributeName;
//NSString *const NSStrokeWidthAttributeName;
//NSString *const NSShadowAttributeName;

- (void)awakeFromNib {
    
    NSDictionary *attribute = @{NSForegroundColorAttributeName : self.textColor,
                                NSFontAttributeName : [self getFont],
                                };
    
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:attribute];
    self.attributedText = attributedText;
    //    self.lineBreakMode = NSLineBreakByCharWrapping;
    
    if (_bgImageName && ![_bgImageName isEmptyString]) {
        if (!CGRectEqualToRect(_rectForCapBackground, CGRectZero)) {//rectForCap이 설정된 경우, 이미지를 리사이즈함.
            
            CGFloat top, left, bottom, right;
            top = CGRectGetMinY(_rectForCapBackground);
            left = CGRectGetMinX(_rectForCapBackground);
            bottom = CGRectGetHeight(_rectForCapBackground);
            right = CGRectGetWidth(_rectForCapBackground);
            
            _bgInsets = UIEdgeInsetsMake(top, left, bottom, right);
        } else {
            _bgInsets = UIEdgeInsetsMake(kfBoxCap, kfBoxCap, kfBoxCap, kfBoxCap);
        }
        
        UIImage *bgImage = [CommonUtil resizableImageWithCapInsets:_bgInsets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:_bgImageName]];
        self.backgroundColor = [UIColor colorWithPatternImage:bgImage];
    } else {
        self.backgroundColor = [UIColor clearColor];
    }
    
    if (!self.highlightedTextColor) {
        self.highlightedTextColor = RGBCOLOR(41, 141, 205);
    }
    
#ifdef DEBUG
    [self setValue:self.text forKey:@"layoutDebuggingIdentifier"];
#endif
}


- (UIFont *)getFont {
    UIFont *font = self.font;
    CGFloat fontSize = self.font.pointSize;
    // TODO: 이부분에서 폰트명에 따라서 처리해야 함
    if ([self.font.fontName isEqualToString:[[UIFont systemFontOfSize:fontSize] fontName]])
    {
        if ([[self.font.fontName lowercaseString] rangeOfString:@"-"].location != NSNotFound) {
            NSString *fontName = [[UIFont systemFontOfSize:fontSize] fontName];
            NSLog(@"Font Name : %@", fontName);
            fontName = [fontName substringToIndex:[fontName rangeOfString:@"-"].location];
            font = [UIFont fontWithName:[NSString stringWithFormat:@"%@-Regular", fontName] size:fontSize];
        }
        
    }
    
    _isBold = [[self.font.fontName lowercaseString] rangeOfString:@"bold"].location != NSNotFound;
    
    return _isBold ? [self boldFont] : font;
}

- (UIFont *)boldFont {
    UIFont *font = self.font;
    CGFloat fontSize = self.font.pointSize;
    
    if ([self.font.fontName isEqualToString:[[UIFont systemFontOfSize:fontSize] fontName]]) {
        NSString *fontName = [[UIFont systemFontOfSize:fontSize] fontName];
        fontName = [fontName substringToIndex:[fontName rangeOfString:@"-"].location];
        font = [UIFont fontWithName:[NSString stringWithFormat:@"%@-Bold", fontName] size:fontSize];
    } else {
        NSString *fontName = font.fontName;
        fontName = [fontName substringToIndex:[fontName rangeOfString:@"-"].location];
        font = [UIFont fontWithName:[NSString stringWithFormat:@"%@-Bold", fontName] size:fontSize];
        font = font ? font : self.font;
    }
    
    return font;
}

- (void)setText:(NSString *)text {
    if (!text || [text isEqualToString:ksEmptyString]) {
        text = ksSpaceString;
    }
    
    text = [text stringByReplacingOccurrencesOfString:@"<br/>" withString:@"\n"];
    
    
#ifdef DEBUG_MODE
    //    text = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@", text, text, text, text, text, text, text, text, text];
#endif
    
    NSDictionary *attribute = @{NSFontAttributeName : [self getFont]};
    
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:attribute];
    self.attributedText = attributedText;
}

- (void)setBold:(NSString *)text {
    if (!text || [text isEmptyString])
        return;
    
    NSDictionary *attribute = @{NSFontAttributeName : [self boldFont]};
    
    
    NSString *lblText = [self.attributedText string];
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    
    //변경될 텍스트의 위치를 찾음
    NSUInteger index = [lblText rangeOfString:text].location;
    NSRange range = NSMakeRange(index, text.length);
    
    if (range.location != NSNotFound) {
        [attrText addAttributes:attribute range:range];
        self.attributedText = attrText;
    }
}

- (void)setFontSize:(CGFloat)fontSize text:(NSString *)text {
    if (!text || [text isEmptyString])
        return;
    
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    NSDictionary *attribute = @{NSFontAttributeName : font};
    
    NSString *lblText = [self.attributedText string];
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    
    //변경될 텍스트의 위치를 찾음
    NSUInteger index = [lblText rangeOfString:text].location;
    NSRange range = NSMakeRange(index, text.length);
    
    if (range.location != NSNotFound) {
        [attrText addAttributes:attribute range:range];
        self.attributedText = attrText;
    }
}

- (void)setRedColor:(NSString *)text {
    [self setColor:[UIColor redColor] text:text];
}

- (void)setBlueColor:(NSString *)text {
    [self setColor:[UIColor blueColor] text:text];
}

- (void)setColor:(UIColor *)color text:(NSString *)text {
    
    NSDictionary *colorAttribute = @{NSForegroundColorAttributeName : color};
    
    NSString *lblText = [self.attributedText string];
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    
    //변경될 텍스트의 위치를 찾음
    NSInteger index = [lblText rangeOfString:text].location;
    NSRange range = NSMakeRange(index, text.length);
    
    if (range.location != NSNotFound) {
        [attrText addAttributes:colorAttribute range:range];
        self.attributedText = attrText;
    }
}

- (void)setUnderLine:(NSString *)text {
    
    NSDictionary *underLineAttribute = @{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
    
    NSString *lblText = [self.attributedText string];
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    //    [attrText addAttributes:@{NSUnderlineStyleAttributeName: } range:NSMakeRange (0, mat.length)];
    
    //변경될 텍스트의 위치를 찾음
    NSInteger index = [lblText rangeOfString:text].location;
    NSRange range = NSMakeRange(index, text.length);
    
    if (range.location != NSNotFound) {
        [attrText addAttributes:underLineAttribute range:range];
        self.attributedText = attrText;
    }
}

- (void)setStrikethrough:(NSString *)text {
    
    NSDictionary *attrStrike = @{NSStrikethroughStyleAttributeName: @(NSUnderlineStyleSingle)};
    
    NSString *lblText = [self.attributedText string];
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    //변경될 텍스트의 위치를 찾음
    NSInteger index = [lblText rangeOfString:text].location;
    NSRange range = NSMakeRange(index, text.length);
    
    if (range.location != NSNotFound) {
        [attrText addAttributes:attrStrike range:range];
        self.attributedText = attrText;
    }
}

- (void)setKern:(NSInteger)kern text:(NSString *)text {
    
    NSDictionary *underLineAttribute = @{NSKernAttributeName : @(kern)};
    
    NSString *lblText = [self.attributedText string];
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    //변경될 텍스트의 위치를 찾음
    NSInteger index = [lblText rangeOfString:text].location;
    NSRange range = NSMakeRange(index, text.length);
    
    if (range.location != NSNotFound) {
        [attrText addAttributes:underLineAttribute range:range];
        self.attributedText = attrText;
    }
}

- (void)setLineSpacing:(CGFloat)lineSpacing {
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    paragraphStyle.alignment = self.textAlignment;
    NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyle};
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.text
                                                                         attributes:attributes];
    self.attributedText = attributedText;
}

- (void)setLink:(NSString *)text{
    [self setColor:[UIColor blueColor] text:text];
    [self setUnderLine:text];
}

- (void)addTarget:(id)target action:(SEL)action {
    _userInteractionTarget = target;
    _userInteractionSelector = action;
    
    UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didLabelTouched:)];
    // if labelView is not set userInteractionEnabled, you must do so
    [self setUserInteractionEnabled:YES];
    [self addGestureRecognizer:gesture];
}

- (void)didLabelTouched:(UIGestureRecognizer*)gestureRecognizer {
    //api contidtion controls
    if (_userInteractionTarget && _userInteractionSelector) {
        
        NSMethodSignature *sig = [_userInteractionTarget methodSignatureForSelector:_userInteractionSelector];
        
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
        
        [invocation setTarget:_userInteractionTarget];                    // index 0 (hidden)
        [invocation setSelector:_userInteractionSelector];                 //index 1 (hidden)
        [invocation setArgument:(__bridge void *)(self) atIndex:2];
        
        [invocation invoke];
    }
}

- (void)addTouchEventHandler:(CustomLabelTouchHandler)handler {
    _touchHandler = handler;
    UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didLabelTouchedWithHandler:)];
    // if labelView is not set userInteractionEnabled, you must do so
    [self setUserInteractionEnabled:YES];
    [self addGestureRecognizer:gesture];
}

- (void)didLabelTouchedWithHandler:(UIGestureRecognizer *)gestureRecognizer {
    UIColor *_tmpColor = self.textColor;
//    self.textColor = self.highlightedTextColor;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.textColor = _tmpColor;
        
        if (_touchHandler) {
            _touchHandler(self);
        }
    });
}

@end

@implementation CustomTopLabel

- (void)drawTextInRect:(CGRect)rect {
    if (self.text) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = self.lineBreakMode;
        CGSize labelStringSize = [self.attributedText boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.frame), CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
        [super drawTextInRect:CGRectMake(0, 0, CGRectGetWidth(self.frame),ceilf(labelStringSize.height))];
    } else {
        [super drawTextInRect:rect];
    }
}

@end
