
#import <Cordova/CDV.h>

#import "HelpshiftPlugin.h"
#import "Helpshift.h"


@implementation HelpshiftPlugin:CDVPlugin

-(NSMutableDictionary*) convertMetaData : (NSMutableDictionary*) config {
    NSMutableDictionary *metaData = nil;
    NSArray *tags = nil;
    if([config objectForKey:@"HSCUSTOMMETADATAKEY"]!= nil) {
        metaData = [config objectForKey:@"HSCUSTOMMETADATAKEY"];
        if([metaData objectForKey:@"HSTAGSKEY"] != nil) {
            tags = [metaData objectForKey:@"HSTAGSKEY"];
            [metaData setObject:tags forKey:HSTagsKey];
            [metaData removeObjectForKey:@"HSTAGSKEY"];
        }
        [config removeObjectForKey:@"HSCUSTOMMETADATAKEY"];
        [config setObject:metaData forKey:HSCustomMetadataKey];
    }
    return config;
}

-(void)install :(CDVInvokedUrlCommand*)command {
    NSString *apiKey = [command argumentAtIndex:0 ];
    NSString *domainName = [command argumentAtIndex:1 ];
    NSString *appId = [command argumentAtIndex:2 ];
    [self.commandDelegate runInBackground:^{
       if([command.arguments count] > 3) {
            NSMutableDictionary *optionsDict = nil;
            optionsDict = [command argumentAtIndex:3 ];
            optionsDict = [self convertMetaData:optionsDict];
            [Helpshift installForApiKey:apiKey domainName:domainName appID:appId withOptions:optionsDict];
        } else {
            [Helpshift installForApiKey:apiKey domainName:domainName appID:appId withOptions:nil];
        }
        [[Helpshift sharedInstance] setDelegate:self];
    }];
}

- (void) showFAQs:(CDVInvokedUrlCommand*)command {
    if([command.arguments count] > 0) {
        NSMutableDictionary *optionsDict = [[NSMutableDictionary alloc] init];
        optionsDict = [command argumentAtIndex:0 ];
        optionsDict = [self convertMetaData:optionsDict];
        [[Helpshift sharedInstance] showFAQs:self.viewController withOptions:optionsDict];
    } else {
        [[Helpshift sharedInstance] showFAQs:self.viewController withOptions:nil];
    }
}

- (void) showConversation:(CDVInvokedUrlCommand*)command {
    if([command.arguments count] > 0) {
        NSMutableDictionary *optionsDict = [[NSMutableDictionary alloc] init];
        optionsDict = [command argumentAtIndex:0 ];
        optionsDict = [self convertMetaData:optionsDict];
        [[Helpshift sharedInstance] showConversation:self.viewController withOptions:optionsDict];
    } else {
        [[Helpshift sharedInstance] showConversation:self.viewController withOptions:nil];
    }
}

- (void) showFAQSection:(CDVInvokedUrlCommand*)command {
    NSString *sectionId = [command argumentAtIndex:0 ];
    if([command.arguments count] > 1) {
        NSMutableDictionary *optionsDict = [[NSMutableDictionary alloc] init];
        optionsDict = [command argumentAtIndex:1 ];
        optionsDict = [self convertMetaData:optionsDict];
        [[Helpshift sharedInstance] showFAQSection:sectionId withController:self.viewController withOptions:optionsDict];
    } else {
        [[Helpshift sharedInstance] showFAQSection:sectionId withController:self.viewController withOptions:nil];
    }
}

- (void) showSingleFAQ:(CDVInvokedUrlCommand*)command {
    NSString *sectionId = [command argumentAtIndex:0 ];
    if([command.arguments count] > 1) {
        NSMutableDictionary *optionsDict = [[NSMutableDictionary alloc] init];
        optionsDict = [command argumentAtIndex:1 ];
        optionsDict = [self convertMetaData:optionsDict];
        [[Helpshift sharedInstance] showSingleFAQ:sectionId withController:self.viewController withOptions:optionsDict];
    } else {
        [[Helpshift sharedInstance] showSingleFAQ:sectionId withController:self.viewController withOptions:nil];
    }
}

- (void) setUserIdentifier:(CDVInvokedUrlCommand *)command {
    NSString *userIdentifier = [command argumentAtIndex:0 ];
    [Helpshift setUserIdentifier:userIdentifier];
}

- (void) setNameAndEmail:(CDVInvokedUrlCommand*)command {
    NSString *userName = [command argumentAtIndex:0 ];
    userName = (userName == NULL ? nil : userName);
    NSString *userEmail = [command argumentAtIndex:1 ];
    userEmail = (userEmail == NULL ? nil : userEmail);
    [Helpshift setName:userName andEmail:userEmail];
}

- (void) leaveBreadCrumb:(CDVInvokedUrlCommand*)command {
    NSString *breadCrumb = [command.arguments objectAtIndex:0];
    [Helpshift leaveBreadCrumb:breadCrumb];
}

- (void) clearBreadCrumbs:(CDVInvokedUrlCommand*)command {
    [[Helpshift sharedInstance] clearBreadCrumbs];
}

-(void)login :(CDVInvokedUrlCommand*)command {
    NSString *identifier = [command argumentAtIndex:0 ];
    NSString *name = [command argumentAtIndex:1 ];
    NSString *email = [command argumentAtIndex:2 ];
    [Helpshift loginWithIdentifier:identifier withName:name andEmail:email];
}

-(void)logout :(CDVInvokedUrlCommand*)command {
    [Helpshift logout];
}

- (void) getNotificationCount:(CDVInvokedUrlCommand*)command {
    NSString *isAsync = [command argumentAtIndex:0 ];
    NSInteger count = [[Helpshift sharedInstance]  getNotificationCountFromRemote:isAsync];
    CDVPluginResult *result;
    NSString *countStr = [NSString stringWithFormat: @"%ld", count];
    result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:countStr];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) registerDeviceToken:(CDVInvokedUrlCommand*)command {
     [[Helpshift sharedInstance] registerDeviceToken : [command argumentAtIndex:0 ]];
}

- (void) registerForRemoteNotifications:(CDVInvokedUrlCommand*)command {
    [[Helpshift sharedInstance] registerForRemoteNotifications];
}

- (void) setSDKLanguage:(CDVInvokedUrlCommand*)command {
    NSString *languageCode = [command argumentAtIndex:0 ];
    [[Helpshift sharedInstance] setSDKLanguage:languageCode];
}

- (void) logE:(CDVInvokedUrlCommand*)command {
    NSString *tag = [command argumentAtIndex:0 ];
    NSString *log = [command argumentAtIndex:1 ];
    NSLog(@"%@ %s %@ %s", @"Error::", [tag UTF8String], @"::", [log UTF8String]);
}

- (void) logW:(CDVInvokedUrlCommand*)command {
    NSString *tag = [command argumentAtIndex:0 ];
    NSString *log = [command argumentAtIndex:1 ];
    NSLog(@"%@ %s %@ %s", @"Warn::", [tag UTF8String], @"::", [log UTF8String]);
}

- (void) logI:(CDVInvokedUrlCommand*)command {
    NSString *tag = [command argumentAtIndex:0 ];
    NSString *log = [command argumentAtIndex:1 ];
    NSLog(@"%@ %s %@ %s", @"Info::", [tag UTF8String], @"::", [log UTF8String]);
}

- (void) logV:(CDVInvokedUrlCommand*)command {
    NSString *tag = [command argumentAtIndex:0 ];
    NSString *log = [command argumentAtIndex:1 ];
    NSLog(@"%@ %s %@ %s", @"Verbose::", [tag UTF8String], @"::", [log UTF8String]);
}

- (void) logD:(CDVInvokedUrlCommand*)command {
    NSString *tag = [command argumentAtIndex:0 ];
    NSString *log = [command argumentAtIndex:1 ];
    NSLog(@"%@ %s %@ %s", @"Debug::", [tag UTF8String], @"::", [log UTF8String]);
}

- (void) showAlertToRateAppWithURL : (CDVInvokedUrlCommand*) command {
    NSString *urlString = [command argumentAtIndex:0  withDefault:nil];
    [Helpshift showAlertToRateAppWithURL:urlString
                     withCompletionBlock:^(HSAlertToRateAppAction action) {
            NSString *rateAppAction = @"";
            switch(action) {
            case HS_RATE_ALERT_CLOSE:
                rateAppAction = @"HS_RATE_ALERT_CLOSE";
                break;
            case HS_RATE_ALERT_FEEDBACK:
                rateAppAction = @"HS_RATE_ALERT_FEEDBACK";
                break;
            case HS_RATE_ALERT_SUCCESS:
                rateAppAction = @"HS_RATE_ALERT_SUCCESS";
                break;
            case HS_RATE_ALERT_FAIL:
                rateAppAction = @"HS_RATE_ALERT_FAIL";
            default:
                break;
            }
            NSString *jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeAppRateResponseCall(\"%s\");", [rateAppAction UTF8String]];
            [self.commandDelegate evalJs:jsString];
        }];
}

- (void) didReceiveNotificationCount:(NSInteger)count{
    NSString *jsString = nil;
    jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeNotificationCall(\"%ld\");", (long)count];
    [self.commandDelegate evalJs:jsString];
}

- (void) didReceiveInAppNotificationWithMessageCount:(NSInteger)count{
    NSString *jsString = nil;
    jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeInAppNotificationCall(\"%ld\");", (long)count];
    [self.commandDelegate evalJs:jsString];
}

- (void) helpshiftSessionHasBegun {
    NSString *jsString = nil;
    jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeSessionBeganCall();"];
    [self.commandDelegate evalJs:jsString];
}

- (void) helpshiftSessionHasEnded {
    NSString *jsString = nil;
    jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeSessionEndedCall();"];
    [self.commandDelegate evalJs:jsString];
}

- (void) newConversationStartedWithMessage:(NSString *)newConversationMessage {
    NSString *jsString = nil;
    jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeNewConversationStartedWithMessageCall(\"%s\");", [newConversationMessage UTF8String]];
    [self.commandDelegate evalJs:jsString];
}

- (void) userRepliedToConversationWithMessage:(NSString *)newMessage {
    NSString *jsString = nil;
    jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeUserRepliedToConversationWithMessageCall(\"%s\");", [newMessage UTF8String]];
    [self.commandDelegate evalJs:jsString];
}

- (void) userCompletedCustomerSatisfactionSurvey:(NSInteger)rating withFeedback:(NSString *)feedback{
    NSString *jsString = nil;
     jsString = [NSString stringWithFormat:@"HelpshiftPlugin._nativeUserCompletedCustomerSatisfactionSurveyCall(\"%ld\",\"%s\");", (long)rating,[feedback UTF8String]];
    [self.commandDelegate evalJs:jsString];
}

@end
