

#import "TML.h"
#import "TMLHtmlDecorationTokenizer.h"
#import "TMLConfiguration.h"

@implementation TMLHtmlDecorationTokenizer


- (NSString *) applyToken: (NSString *) token toValue: (NSString *) value {
    if ([token isEqualToString:TML_RESERVED_TOKEN] || ![self isTokenAllowed:token])
        return value;
    
    id decoration = [self.tokensData objectForKey:token];
    
    if (decoration == nil || [decoration isKindOfClass:NSDictionary.class]) {
        decoration = [[[TML sharedInstance] configuration] defaultTokenValueForName:token
                                                                               type:TMLDecorationTokenType
                                                                             format:TMLHTMLTokenFormat];
        if (decoration == nil) return value;

        NSString *defaultValue = [((NSString *) decoration) stringByReplacingOccurrencesOfString:TML_PLACEHOLDER withString:value];

        if ([decoration isKindOfClass:NSDictionary.class]) {
            for (NSString *key in [decoration allKeys]) {
                NSString *param = [NSString stringWithFormat:@"{$%@}", key];
                defaultValue = [defaultValue stringByReplacingOccurrencesOfString:param withString:[decoration objectForKey:key]];
            }
        }
        
        return defaultValue;
    }

    if ([decoration isKindOfClass:NSClassFromString(@"NSBlock")]) {
        NSString *(^fn)(NSString *) = decoration;
        return fn(value);
    }
    
    if ([decoration isKindOfClass:NSString.class]) {
        NSString *string = (NSString *) decoration;
        return [string stringByReplacingOccurrencesOfString:TML_PLACEHOLDER withString:value];
    }
    
    return value;
}


@end
