/*
 *      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.
 */

/*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);
    }
}

/

/ Return GetSocial instance /

GetSocial.getInstance = function () {
    if (!this.instance) {
        this.instance = new GetSocial();
    }
    return this.instance;
}

/

/ The method sets your app login data, it must be called before using any other functionality offered by the SDK. / / Your app’s key, can be found in the GetSocial developer console / Action called if operation was successful. Optional. / Action called if operation failed to complete. Optional.

GetSocial.prototype.init = function(key, onSuccess, onFailure) {
    cordova.exec(onSuccess, onFailure, NATIVE_BRIDGE_NAME, "init", [key]);
}

/

/ Returns the current SDK version / / Action called with version as argument.

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

/

/ Returns the current SDK APIversion / / Action called with apiversion as argument.

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

/

/ Returns the current Environment / / Action called with Environment as argument. Can Android or iOS

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

/

/ Returns all supported invite providers. / / Action called with array containing constants id’s for all supported providers

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

/

/ Returns configuration. / / Action called with null as argument.

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]);
}

/

/ Provide a method that implements OnReferralDataReceived delegate if you would like to get referral data if the user installs or opens the app after opening a Smart Invite . / / Return refferalData in format [{key:value, key2:value2}, …]

GetSocial.prototype.setOnReferralDataReceivedListener = function (onReferralDataReceived) {
    cordova.exec(onReferralDataReceived, this.onErrorPlugin, NATIVE_BRIDGE_NAME, "setOnReferralDataReceivedListener", []);
}

/

/ Sets the actions to be called when smart invites are triggered / / Action to be called when user clicked on specific invite provider. / Action to be called when user send invites. Gets number of invitations sent as a parameter.

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", []);
}

/

/ Invite friends through a specific invite provider. / / The provider through which the invite will be sent. / The subject to be sent with the invite. If it is null the default subject set on DevPortal is sent. / 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. / The image path, or null if no image should be shown. / The bundle to be sent with the invite. It can be null. / Action called when invoke inviteFriendsUsingProvider.

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]);
    }

/

/ Register a new instance of a plugin for a specified provider. / / An instance of a plugin implementation / Action called with callbackId as argument.

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()]);
}

/

/ Return CurrentUser. / / Action called with user data in json as argument.

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", []);
}

/

/ Post an activity on the activity feed. / / The text of the activity, or null if no text should be shown. / The image path, or null if no image should be shown. / The text of the activity button, or null if no button text should be shown. / The action generated on click, or null if no button or image is shown. / Tags for user segmentation. / Action called if operation was successful. / Action called if operation failed to complete.

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]);
}

/

/ Sets the action to be called when new chat message or notification arrives. First param is new notifications number, second - unread chat messages number. /

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;
h