//
//  Emojione.m
//
//  Created by Alessandro Calzavara on 16/12/14.
//  Copyright (c) 2014 Spreaker, Inc.
//

#import "Emojione.h"

@implementation Emojione

+ (NSString *)shortnameToUnicode:(NSString *)string
{
    static NSDictionary * emojiMapping;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        emojiMapping = [self _loadShortNameToUnicode];
    });

    NSString * SHORTNAME_PATTERN = @":([-+\\w]+):";

    NSMutableString * unicodeString = [string mutableCopy];
    NSError * error = nil;
    NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:SHORTNAME_PATTERN
                                                                            options:0
                                                                              error:&error];

    NSAssert(!error, @"Unable to create regex: ", error);

    NSArray * matches = [regex matchesInString:unicodeString
                                       options:0
                                         range:NSMakeRange(0, [unicodeString length])];
    
    for (NSTextCheckingResult * result in [matches reverseObjectEnumerator]) {

        if ([result numberOfRanges] < 2) {
            continue;
        }
        
        // Range 0: full shortname
        // Range 1: shortname without :
        
        NSString * shortname = [string substringWithRange:[result rangeAtIndex:1]];
        NSString * emoji = [emojiMapping objectForKey:shortname];
        if (emoji) {
            [unicodeString replaceCharactersInRange:[result rangeAtIndex:0]
                                         withString:emoji];
        }
    }

    return unicodeString;
}

+ (NSDictionary *)_loadShortNameToUnicode
{
    // Mapping generated by script.

    return @{
        <%= mapping %>
            };
}

@end
