GetSocial Cordova SDK

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.

SmartInviteViewBuilder

declaration
 SmartInviteViewBuilder 

global cordova, module

var SmartInviteViewBuilder = require('./SmartInviteViewBuilder')
var Leaderboard = require('./Leaderboard')

var NATIVE_BRIDGE_NAME = "GetSocialCordova";

var INVITE_FRIENDS_EVENTS = {
    ON_INVITE_FRIENDS_INTENT_EVENT: 0,
    ON_INVITED_FRIENDS_EVENT: 1
}

var PLUGIN_EVENT = {
    INVITE_FRIENDS: "inviteFriends",
    INIT_CALLBACK_ID: "initCallbackId"
}

var SCORES_TYPE = {
    SCORE_TYPE_WORLD: "score_type_world",
    SCORE_TYPE_FOLLOWING: "score_type_following",
    SCORE_TYPE_OTHERS: "score_type_others"
}

var GetSocial = function() {

    this.instance = null;

    this.onErrorPlugin = function(err) {
        console.log(err);
    }
}



/// <summary>
/// Return GetSocial instance
/// </summary>
GetSocial.getInstance = function () {
    if (!this.instance) {
        this.instance = new GetSocial();
    }
    return this.instance;
}


/// <summary>
/// The method sets your app login data, it must be called before using any other functionality offered by the SDK.
/// </summary>
/// <param name="key">Your app's key, can be found in the GetSocial developer console</param>
/// <param name="onSuccess">Action called if operation was successful. Optional.</param>
/// <param name="onFailure">Action called if operation failed to complete. Optional.</param>
GetSocial.prototype.init = function(key, onSuccess, onFailure) {
    cordova.exec(onSuccess, onFailure, NATIVE_BRIDGE_NAME, "init", [key]);
}

/// <summary>
/// Returns the current SDK version
/// </summary>
/// <param name="onResult">Action called with version as argument.</param>
GetSocial.prototype.getVersion = function (onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "getVersion", []);
}
/// <summary>
/// Returns the current SDK APIversion
/// </summary>
/// <param name="onResult">Action called with apiversion as argument.</param>
GetSocial.prototype.getApiVersion = function (onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "getApiVersion", []);
}
/// <summary>
/// Returns the current Environment
/// </summary>
/// <param name="onResult">Action called with Environment as argument. Can <c>Android</c> or <c>iOS</c> </param>
GetSocial.prototype.getEnvironment = function (onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "getEnvironment", []);
}
/// <summary>
/// Returns all supported invite providers.
/// </summary>
/// <param name="onResult">Action called with array containing constants id's for all supported providers</returns>
GetSocial.prototype.getSupportedInviteProviders = function (onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "getSupportedInviteProviders", []);
}
/// <summary>
/// Returns configuration.
/// </summary>
/// <param name="onResult">Action called with null as argument.</param>
GetSocial.prototype.getConfiguration = function (onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "getConfiguration", []);
}

GetSocial.prototype.setOnUserAvatarClickHandler = function(onResult) {
    cordova.exec(function(data) {
                         //data = JSON.parse(data);
                         var user = new GetSocial.CurrentUser(data.user);
                         onResult(user, data.source);
                     }, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnUserAvatarClickHandler");
}

GetSocial.prototype.setOnAppAvatarClickHandler = function(onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnAppAvatarClickHandler");
}

GetSocial.prototype.setOnActivityActionClickListener = function(onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnActivityActionClickListener");
}

GetSocial.prototype.setOnInviteButtonClickListener = function(onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnInviteButtonClickListener");
}

GetSocial.prototype.setOnActionPerformListener = function(onResult) {
    cordova.exec(function(data) {
       onResult(data.action, data.actionFinalizerHash);
    }, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnActionPerformListener", []);
}

GetSocial.prototype.finalizeAction = function(actionFinalizerHash, value, onResult) {
    cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "finalizeAction", [actionFinalizerHash, value]);
}


/// <summary>
/// Provide a method that implements <c>OnReferralDataReceived</c> delegate if you would like to get referral data if the user installs or opens the app after opening a Smart Invite .
/// </summary>
/// <param name="onReferralDataReceived">Return refferalData in format [{key:value, key2:value2}, ...]</param>
GetSocial.prototype.setOnReferralDataReceivedListener = function (onReferralDataReceived) {
    cordova.exec(onReferralDataReceived, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnReferralDataReceivedListener", []);
}

/// <summary>
/// Sets the actions to be called when smart invites are triggered
/// </summary>
/// <param name="onInviteFriendsIntent">Action to be called when user clicked on specific invite provider.</param>
/// <param name="onFriendsInvited">Action to be called when user send invites. Gets number of invitations sent as a parameter.</param>
GetSocial.prototype.setOnInviteFriendsListener = function (onInviteFriendsIntent, onFriendsInvited ) {
        cordova.exec(function(jsonObj) {
            if(jsonObj != undefined) {
                if(jsonObj.Event == INVITE_FRIENDS_EVENTS.ON_INVITE_FRIENDS_INTENT_EVENT) {
                    onInviteFriendsIntent();
                } else if(jsonObj.Event == INVITE_FRIENDS_EVENTS.ON_INVITED_FRIENDS_EVENT) {
                    onFriendsInvited(jsonObj.InvitedFriends);
                }
            }
        }, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnInviteFriendsListener", []);
}
/// <summary>
/// Invite friends through a specific invite provider.
/// </summary>
/// <param name="provider">The provider through which the invite will be sent.</param>
/// <param name="subject">The subject to be sent with the invite. If it is null the default subject set on DevPortal is sent.</param>
/// <param name="text">The text to be sent with the invite. NOTE: you can use following tags to customize text: [APP_INVITE_URL] - tag is replaced with url to download the app; [APP_NAME] - tag is replaced with app name configured on the GetSocial Developer Portal. If it is null the default text set on DevPortal is sent.</param>
/// <param name="imagePath">The image path, or null if no image should be shown.</param>
/// <param name="referralData">The bundle to be sent with the invite. It can be null.</param>
/// <param name="onResult">Action called when invoke inviteFriendsUsingProvider.</param>
GetSocial.prototype.inviteFriendsUsingProvider = function (provider, subject, text, imagePath, referralData, onResult) {
        var option = {}
        if(provider == null) {
            errorCallback("Please set provider value");
            return
        }
        option.provider = provider;

        if(subject != null) {
            option.subject = subject;
        }
        if(text != null) {
           option.text = text;
        }

        if(imagePath != null) {
           option.imagePath = imagePath;
        }

        if(referralData != null) {
           option.referrals = referralData;
        }

        cordova.exec(onResult, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "inviteFriendsUsingProvider", [option]);
    }
/// <summary>
/// Register a new instance of a plugin for a specified provider.
/// </summary>
/// <param name="plugin">An instance of a plugin implementation</param>
/// <param name="onResult">Action called with callbackId as argument.</param>
GetSocial.prototype.registerPlugin = function (onResult, plugin) {
    if (!(plugin instanceof GetSocial.InvitePlugin))
        return false;

    cordova.exec(function(data) {
        var action = data.action;
        if(action == null)
            return;

        if (action === PLUGIN_EVENT.INIT_CALLBACK_ID) {
            plugin.setCallbackId(data.callbackId)
            onResult(data.callbackId);
        }
        if(action === PLUGIN_EVENT.INVITE_FRIENDS) {
            var subject = data.subject;
            var text = data.text;
            var referralDataUrl = data.referralDataUrl;
            var image = data.image;
            plugin.inviteFriends(subject, text, referralDataUrl, image);
        }

    }, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "registerPlugin", [plugin.getOptions()]);
}

/// <summary>
/// Return CurrentUser.
/// </summary>
/// <param name="onResult">Action called with user data in json as argument.</param>
GetSocial.prototype.getCurrentUser = function(onResult) {
    cordova.exec(function(data) {
        //if(typeof data === 'string') {
            data = JSON.parse(data);
        //}
        var user = new GetSocial.CurrentUser(data);
        onResult(user);
    }, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "getCurrentUser", []);
}

/// <summary>
/// Post an activity on the activity feed.
/// </summary>
/// <param name="text">The text of the activity, or null if no text should be shown.</param>
/// <param name="imagePath">The image path, or null if no image should be shown.</param>
/// <param name="buttonText">The text of the activity button, or null if no button text should be shown.</param>
/// <param name="actionId">The action generated on click, or null if no button or image is shown.</param>
/// <param name="tags">Tags for user segmentation.</param>
/// <param name="onSuccess">Action called if operation was successful.</param>
/// <param name="onFailure">Action called if operation failed to complete.</param>
GetSocial.prototype.postActivity = function(text, imagePath, buttonText, actionId, tags, onResult, onError) {
    var option = {};
    if(text != null)
        option.text = text;

    if(imagePath != null) 
        option.imagePath = imagePath;

    if(buttonText != null) 
        option.buttonText = buttonText;

    if(actionId != null) 
        option.actionId = actionId;

    if(tags != null) 
        option.tags = tags;

    cordova.exec(onResult, onError, NATIVE_BRIDGE_NAME, "postActivity", [option]);
}

/// <summary>
/// Sets the action to be called when new chat message or notification arrives. First param is new notifications number, second - unread chat messages number.
/// </summary>
GetSocial.prototype.setOnUnreadNotificationsCountChangeListener = function(onUnreadNotificationsCountChangeListener) {
    cordova.exec(onUnreadNotificationsCountChangeListener, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnUnreadNotificationsCountChangeListener", []);
}

GetSocial.prototype.getLeaderboard = function(leaderboard, onResult, onError) {
    cordova.exec(function(data) {
        data = JSON.parse(data);

        var leaderboard = new GetSocial.Leaderboard(data);

        onResult(leaderboard);
    }, onError, NATIVE_BRIDGE_NAME, "getLeaderboard", [leaderboard]);
}

GetSocial.prototype.getLeaderboards = function(leaderboards, end, onResult, onError) {
    if( Array.isArray(leaderboards)) {
        cordova.exec(function(data) {
            console.log(data);
            var result = [];
            for(var i=0; i < data.length; i++ ) {
                result.push(new GetSocial.Leaderboard(JSON.parse(data[i])));
            }

            end(result);
        }, onResult, NATIVE_BRIDGE_NAME, "getLeaderboardsArray", [leaderboards]);
    } else if(typeof leaderboards == 'number' && typeof end == 'number') {
        cordova.exec(function(data) {
            console.log(data);
            var result = [];
            for(var i=0; i < data.length; i++ ) {
                result.push(new GetSocial.Leaderboard(JSON.parse(data[i])));
            }

            onResult(result);
        }, onError, NATIVE_BRIDGE_NAME, "getLeaderboardsInterval", [leaderboards, end]);
    }
}

GetSocial.prototype.getLeaderboardScores = function(leaderboard, start, end, type, onResult, onError) {
    var object = {
        id: leaderboard,
        start: start,
        end: end,
        type: type
    };
    cordova.exec(function(data) {
        var result = [];
        for(var i=0; i < data.length; i++) {
            if(typeof data[i]  === 'string') {
                data[i] = JSON.parse(data[i]);
            }
            result.push(new GetSocial.LeaderboardScore(data[i]));
        }
        onResult(result);
    }, onError, NATIVE_BRIDGE_NAME, "getLeaderboardScores", [object]);
}

GetSocial.prototype.submitLeaderboardScore = function(leaderboardId, value, onResult, onError) {
    var object = {
        id: leaderboardId,
        value: value
    };
    cordova.exec(onResult, onError, NATIVE_BRIDGE_NAME, "submitLeaderboardScore", [object]);
}

GetSocial.prototype.submitLeaderboardScore = function(leaderboardId, value, onResult, onError) {
    var object = {
        id: leaderboardId,
        value: value
    };
    cordova.exec(onResult, onError, NATIVE_BRIDGE_NAME, "submitLeaderboardScore", [object]);
}

GetSocial.prototype.save = function(data, onResult, onError) {
    cordova.exec(onResult, onError, NATIVE_BRIDGE_NAME, "cloudSaveData", [data]);
}

GetSocial.prototype.getLastSave = function(onResult, onError) {
    cordova.exec(onResult, onError, NATIVE_BRIDGE_NAME, "getCloudSaveData", []);
}

GetSocial.prototype.setLanguage = function(language, onResult, onError) {
    cordova.exec(onResult, onError, NATIVE_BRIDGE_NAME, "setLanguage", [language]);
}

GetSocial.prototype.getLanguage = function(onResult, onError) {
    cordova.exec(onResult, onError, NATIVE_BRIDGE_NAME, "getLanguage", []);
}


module.exports = GetSocial;