/********* Peer5.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>
#import "Peer5Kit/Peer5Sdk.h"

static Peer5Sdk* sdk;

@interface Peer5 : CDVPlugin {}

- (void)init:(CDVInvokedUrlCommand*)command;
- (void)getStreamUrl:(CDVInvokedUrlCommand*)command;
@end

@implementation Peer5

- (void)init:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;
    NSString* token = [command.arguments objectAtIndex:0];

    if (token == nil || [token length] == 0) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    } else {
        if (sdk != nil) { // already have SDK
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return;
        }
        sdk = [[Peer5Sdk alloc] initWithToken:token];
        if (sdk != nil) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
        }
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)getStreamUrl:(CDVInvokedUrlCommand*)command 
{
    CDVPluginResult* pluginResult = nil;
    NSString* url = [command.arguments objectAtIndex:0];
    NSURL* original = [NSURL URLWithString:url];
    if (original == nil) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:url];
    } else {
        NSURL* url = [sdk streamURLForURL :original];
        NSString* ret = [url absoluteString];
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:ret];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}
@end
