//
//  HWMFormatter.m
//  HWMUISDKNativeDemo
//
//

#import "HWMFormatter.h"

@interface HWMFormatter ()

@property (nonatomic, copy) NSString *allowdCharacter; // 允许输入的字符串

@end

@implementation HWMFormatter

- (instancetype)init {
    self = [super init];
    if (self) {
        self.formatterStyle = HWMFormatterStyleAll;
    }
    return self;
}

- (void)setFormatterStyle:(HWMFormatterStyle)formatterStyle
{
    _formatterStyle = formatterStyle;
    if (formatterStyle == HWMFormatterStyleNumber) {
        self.allowdCharacter = @"1234567890";
    } else {
        self.allowdCharacter = @"";
    }
}

- (BOOL)getObjectValue:(id *)object forString:(NSString *)string errorDescription:(NSString **)error
{
    *object = string;
    return YES;
}


- (NSString *)stringForObjectValue:(id)object
{
    return (NSString *)object;
}

- (BOOL)isPartialStringValid:(NSString **)partialStringPtr
       proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
              originalString:(NSString *)origString
       originalSelectedRange:(NSRange)origSelRange
            errorDescription:(NSString **)error
{
    if (self.allowdCharacter.length) {
        NSRange passwordRange;
        NSString *strLetterDigital = self.allowdCharacter;
        NSString *strPassword;
        //使用characterSetWithCharactersInString初始化字符集
        NSCharacterSet *charactersetDigitAndLetter = [NSCharacterSet characterSetWithCharactersInString:strLetterDigital];
        charactersetDigitAndLetter = [charactersetDigitAndLetter invertedSet];
        passwordRange = NSMakeRange(origSelRange.location,
                                    proposedSelRangePtr->location
                                    - origSelRange.location);
        strPassword = [*partialStringPtr substringWithRange: passwordRange];
        if ([strPassword rangeOfCharacterFromSet:charactersetDigitAndLetter
                                         options:NSLiteralSearch].location != NSNotFound) {
            *error = @"输入的文字不合法";
            return(NO);
        } else {
            *error = nil;
            return(YES);
        }
    }
    return YES;
}

- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attributes {
    return nil;
}

@end
