//
//  NSString+OJAKit.m
//  OJAKitDemo
//
//  Created by luxiaoming on 16/7/4.
//  Copyright © 2016年 luxiaoming. All rights reserved.
//

#import "NSString+OJAKit.h"

@implementation NSString (OJAKit)


- (CGFloat)heightForWidth:(CGFloat)width withAttributes:(nullable NSDictionary<NSString *, id> *)attributes {
    CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
    return [self sizeForMaxSize:maxSize withAttributes:attributes].height;
}

/**
 *  用系统的boundsWithRect的方法计算出来的string高度，并用ceil函数处理返回结果
 *  用style设置行高的方式，可以比较完美的解决兼容emoji表情的问题
 *  注意！！！如果不是NSLineBreakByWordWrapping或者NSLineBreakByCharWrapping，这个方法将
    使用NSLineBreakByWordWrapping的方式来计算
 */
- (CGSize)sizeForMaxSize:(CGSize)maxSize withAttributes:(nullable NSDictionary<NSString *, id> *)attributes {
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:attributes];
    NSMutableParagraphStyle *style = [[dict objectForKey:NSParagraphStyleAttributeName] mutableCopy];
    if (style && (style.lineBreakMode == NSLineBreakByTruncatingTail ||
                  style.lineBreakMode == NSLineBreakByTruncatingHead ||
                  style.lineBreakMode == NSLineBreakByTruncatingMiddle ||
                  style.lineBreakMode == NSLineBreakByClipping)) {
        style.lineBreakMode = NSLineBreakByWordWrapping;
        [dict setObject:style forKey:NSParagraphStyleAttributeName];
    }
    
    CGRect rect = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dict context:nil];
    return CGSizeMake(ceil(rect.size.width), ceil(rect.size.height));
}

/**
 *  判断string是否合法，如何不为nil且length>0返回yes，其他返回NO
 */
- (BOOL)isValidString {
    if (![self isKindOfClass:[NSString class]]) {
        return NO;
    }
    if (self && self.length > 0) {
        return YES;
    } else {
        return NO;
    }
}



#pragma mark -






/**
 将浮点数转为 四舍五入到整数 的字符串，避免显示的时候出现.99999999之类
 */
+ (NSString *)roundedStringForFloat:(CGFloat)floatNumber {
    return [self roundedStringWithDecimalCount:0 forFloat:floatNumber];
}

/**
 将浮点数转为 四舍五入保留count位小数 的字符串，避免显示的时候出现.99999999之类
 */
+ (NSString *)roundedStringWithDecimalCount:(NSInteger)count forFloat:(CGFloat)floatNumber {
    //注意：用下面这种方式会自动四舍五入，而直接用(int)floatNumber的方式会按整数截断
    if (count == 0) {
        return [NSString stringWithFormat:@"%.0f", floatNumber];
    }
    else if (count == 1) {
        return [NSString stringWithFormat:@"%.1f", floatNumber];
    }
    else {
        return [NSString stringWithFormat:@"%.2f", floatNumber];
    }
}




@end
