/*
 *    	Copyright 2015-2016 GetSocial B.V.
 *
 *	Licensed under the Apache License, Version 2.0 (the "License");
 *	you may not use this file except in compliance with the License.
 *	You may obtain a copy of the License at
 *
 *    	http://www.apache.org/licenses/LICENSE-2.0
 *
 *	Unless required by applicable law or agreed to in writing, software
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License.
 */

#import "GetSocialPluginEvents.h"

@implementation GetSocialPluginEvents

- (GetSocialPluginProxy *)getSocialPluginProxy:(NSString *)callbackId
{
    if ([GetSocialCordova registeredPlugins] == nil) return nil;

    for (int i = 0; i < [[GetSocialCordova registeredPlugins] count]; i++)
    {
        if ([[[[GetSocialCordova registeredPlugins] objectAtIndex:i] callbackId] isEqualToString:callbackId])
        {
            return [[GetSocialCordova registeredPlugins] objectAtIndex:i];
        }
    }

    return nil;
}

- (void)completeCallback:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *pluginCallbackId = [[command arguments] objectAtIndex:0];

    GetSocialPluginProxy *plugin = [self getSocialPluginProxy:pluginCallbackId];
    if (plugin != nil)
    {
        [plugin onComplete:nil];
        [self successWithCallbackId:callbackId];
        return;
    }

    [self errorWithMsg:@"Not found plugin" andCallbackId:callbackId];
}

- (void)cancelCallback:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *pluginCallbackId = [[command arguments] objectAtIndex:0];

    GetSocialPluginProxy *plugin = [self getSocialPluginProxy:pluginCallbackId];
    if (plugin != nil)
    {
        [plugin onCancel];
        [self successWithCallbackId:callbackId];
        return;
    }

    [self errorWithMsg:@"Not found plugin" andCallbackId:callbackId];
}

- (void)errorCallback:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    NSString *pluginCallbackId = [[command arguments] objectAtIndex:0];

    GetSocialPluginProxy *plugin = [self getSocialPluginProxy:pluginCallbackId];
    if (plugin != nil)
    {
        [plugin onError];
        [self successWithCallbackId:callbackId];
        return;
    }

    [self errorWithMsg:@"Not found plugin" andCallbackId:callbackId];
}

- (void)clickedCallback:(CDVInvokedUrlCommand *)command
{
    NSString *callbackId = [command callbackId];
    [self successWithCallbackId:callbackId];
}
@end
