//
//  IconGenerator.m
//  ReactNativeIcons
//
//  Created by Cory Smith on 2015-03-31.
//  Copyright (c) 2015 Facebook. All rights reserved.
//

#import "IconGenerator.h"
#import "FontAwesomeKit.h"
#import "RCTLog.h"

@implementation IconGenerator

- (UIImage *)createImageForIcon:(NSString *)iconName color:(UIColor *)color size:(int)size {
    NSString *theIconName = iconName;
    NSArray *parts = [theIconName componentsSeparatedByString:@"|"];
    NSString *fontPrefix = parts[0];
    NSString *iconIdentifier = parts[1];
    
    id target;
    if([fontPrefix isEqualToString:@"fontawesome"]) {
        target = [FAKFontAwesome class];
    } else if([fontPrefix isEqualToString:@"ion"]) {
        target = [FAKIonIcons class];
    } else if([fontPrefix isEqualToString:@"zocial"]) {
        target = [FAKZocial class];
    } else if([fontPrefix isEqualToString:@"foundation"]) {
        target = [FAKFoundationIcons class];
    }
    
    SEL selector = NSSelectorFromString([NSString stringWithFormat:@"%@IconWithSize:",[self camelcase:iconIdentifier]]);
    
    if(!target || ![target respondsToSelector:selector]) {
        if(target) {
            NSLog(@"No icon '%@' in '%@' icon font", iconIdentifier, fontPrefix);
            RCTLogError(@"No icon '%@' in '%@' icon font", iconIdentifier, fontPrefix);
        } else {
            NSLog(@"No icon font named '%@'", fontPrefix);
            RCTLogError(@"No icon font named '%@'", fontPrefix);
        }
        return nil;
    }
    
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]];
    [inv setSelector:selector];
    [inv setTarget:target];
    [inv setArgument:&size atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
    [inv retainArguments];
    [inv invoke];
    
    CFTypeRef result;
    [inv getReturnValue:&result];
    
    FAKIcon *icon = (__bridge id)result;
    [icon setAttributes:@{NSForegroundColorAttributeName: color}];
    
    UIImage *image = [icon imageWithSize:CGSizeMake(size,size)];
    return image;
}

- (NSString *)camelcase:(NSString *)stringToCamelcase
{
    NSArray *components = [stringToCamelcase componentsSeparatedByString:@"-"];
    NSMutableString *output = [NSMutableString string];
    
    for (NSUInteger i = 0; i < components.count; i++) {
        if (i == 0) {
            [output appendString:components[i]];
        } else {
            [output appendString:[components[i] capitalizedString]];
        }
    }
    
    return [NSString stringWithString:output];
}

@end
