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

package im.getsocialsdk.cordova.plugin;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.Uri;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import im.getsocial.sdk.core.CurrentUser;
import im.getsocial.sdk.core.GetSocial;
import im.getsocial.sdk.core.UI.builder.ActivitiesViewBuilder;
import im.getsocial.sdk.core.UI.builder.NotificationsViewBuilder;
import im.getsocial.sdk.core.UI.builder.SmartInviteViewBuilder;
import im.getsocial.sdk.core.UI.builder.UserListViewBuilder;
import im.getsocial.sdk.core.User;
import im.getsocial.sdk.core.Utilities;
import im.getsocial.sdk.core.configuration.Configuration;
import im.getsocial.sdk.core.resources.Leaderboard;
import im.getsocial.sdk.core.resources.LeaderboardScore;

public class GetSocialCordova extends CordovaPlugin {
    private final String TAG = "GetSocialCordova_Plugin";

    private GetSocial mGetSocialImpl;

    public static Map<String, GetSocialPluginProxy> registeredPlugins;
    public static Map<Integer, GetSocial.OnActionPerformListener.ActionFinalizer> actionFinalizer;

    private final String INIT_METHOD = "init";
    private final String IS_INITIALIZED_METHOD = "isInitialized";
    private final String GET_VERSION_METHOD = "getVersion";
    private final String GET_API_VERSION_METHOD = "getApiVersion";
    private final String GET_ENVIROMENT_METHOD = "getEnvironment";
    private final String GET_CONFIGURATION_VERSION_METHOD = "getConfiguration";
    private final String SET_ON_USER_AVATAR_CLICK_HANDLER_METHOD = "setOnUserAvatarClickHandler";
    private final String SET_ON_APP_AVATAR_CLICK_HANDLER_METHOD  = "setOnAppAvatarClickHandler";
    private final String SET_ON_ACTIVITY_ACTION_CLICK_LISTENER_METHOD = "setOnActivityActionClickListener";
    private final String SET_ON_INVITE_BUTTON_CLICK_LISTENER_METHOD = "setOnInviteButtonClickListener";
    private final String SET_ON_ACTION_PERFORM_LISTENER_METHOD = "setOnActionPerformListener";
    private final String FINALIZE_ACTION_METHOD = "finalizeAction";
    private final String SET_ON_INVITE_FRIENDS_LISTENER_METHOD = "setOnInviteFriendsListener";
    private final String SET_ON_REFERAL_DATA_RECEIVED_LISTENER_METHOD = "setOnReferralDataReceivedListener";
    private final String GET_SUPPORTED_INVITE_PROVIDERS_METHOD = "getSupportedInviteProviders";
    private final String INVITE_FRIENDS_USING_PROVIDER_METHOD = "inviteFriendsUsingProvider";
    private final String REGISTER_PLUGIN_METHOD = "registerPlugin";
    private final String CREATE_SMART_INVITE_VIEW_METHOD = "createSmartInviteView";
    private final String CLOSE_SMART_INVITE_VIEW_METHOD = "closeSmartInviteView";
    private final String GET_CURRENT_USER = "getCurrentUser";
    private final String CREATE_ACTIVITIES_VIEW_METHOD = "createActivitiesView";
    private final String CLOSE_ACTIVITIES_VIEW_METHOD = "closeActivitiesView";
    private final String POST_ACTIVITY_METHOD = "postActivity";
    private final String CREATE_NOTIFICATIONS_VIEW_METHOD = "createNotificationsView";
    private final String SET_ON_UNREAD_NOTIFICATIONS_COUNT_LISTENER_METHOD = "setOnUnreadNotificationsCountChangeListener";
    private final String CLOSE_NOTIFICATIONS_VIEW_METHOD = "closeNotificationsView";
    private final String CREATE_USER_LIST_VIEW_METHOD = "createUserListView";
    private final String CLOSE_USER_LIST_VIEW_METHOD = "closeUserListView";
    private final String GET_LEADRBOARD_VIEW_METHOD = "getLeaderboard";
    private final String GET_LEADRBOARDS_ARRAY_VIEW_METHOD = "getLeaderboardsArray";
    private final String GET_LEADRBOARDS_INTERVAL_VIEW_METHOD = "getLeaderboardsInterval";
    private final String GET_LEADRBOARDS_SCORES_VIEW_METHOD = "getLeaderboardScores";
    private final String SUBMIT_LEADERBOARD_SCORE_VIEW_METHOD = "submitLeaderboardScore";
    private final String SUBMIT_CLOUD_SAVE_VIEW_METHOD = "cloudSaveData";
    private final String SUBMIT_GET_CLOUD_SAVE_VIEW_METHOD = "getCloudSaveData";
    private final String SET_LANGUAGE_METHOD = "setLanguage";
    private final String GET_LANGUAGE_METHOD = "getLanguage";

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        if(GetSocialCordova.actionFinalizer == null)
            GetSocialCordova.actionFinalizer = new HashMap<Integer, GetSocial.OnActionPerformListener.ActionFinalizer>();
    }

    @Override
    public void onResume(boolean multitasking) {
        super.onResume(multitasking);
        getSocialImpl().onResume(this.cordova.getActivity());
    }

    @Override
    public void onPause(boolean multitasking) {
        super.onPause(multitasking);
        getSocialImpl().onPause();
    }

    private GetSocial getSocialImpl() {
        if(this.mGetSocialImpl == null) {
            this.mGetSocialImpl = GetSocial.getInstance();
        }

        return this.mGetSocialImpl;
    }

    private void init(final String key, final CallbackContext callbackContext) {
        final Context ctx = this.cordova.getActivity().getApplicationContext();
        cordova.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                getSocialImpl().init(ctx, key, new GetSocial.OperationObserver() {
                            @Override
                            public void onSuccess(String data)
                            {
                                callbackContext.success(data);
                                Log.d(TAG, "GetSocial initialization successful");
                            }

                            @Override
                            public void onFailure(String error)
                            {
                                callbackContext.error("GetSocial initialization failed");
                                Log.d(TAG, "GetSocial initialization failed, error: " + error);
                            }
                        });
            }
        });
    }
    private boolean isInitialized() {
        return getSocialImpl().isInitialized();
    }
    private String getVersion() {
        return GetSocial.VERSION;
    }
    private String getApiVersion() {
        return GetSocial.API;
    }
    private String getEnvironment() {
        return "Android";
    }
    private Configuration getConfiguration() {
        return getSocialImpl().getConfiguration();
    }
    private void setOnInviteFriendsListener(final CallbackContext callbackContext) {
        getSocialImpl().setInviteFriendsListener(new GetSocial.InviteFriendsListener() {
            private final int ON_INVITE_FRIENDS_INTENT_EVENT = 0;
            private final int ON_INVITED_FRIENDS_EVENT = 1;
            @Override
            public void onInviteFriendsIntent() {
                JSONObject obj = new JSONObject();
                try {
                    obj.put("Event", ON_INVITE_FRIENDS_INTENT_EVENT);
                } catch (Exception e) {}
                sentResult(obj);
            }

            @Override
            public void onInvitedFriends(int i) {
                JSONObject obj = new JSONObject();
                try {
                    obj.put("Event", ON_INVITED_FRIENDS_EVENT);
                    obj.put("InvitedFriends", i);
                } catch (Exception e) {}
                sentResult(obj);
            }

            public void sentResult(JSONObject obj) {
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        });
    }
    private void setOnReferralDataReceivedListener(final CallbackContext callbackContext) {
        getSocialImpl().setOnReferralDataReceivedListener(new GetSocial.OnReferralDataReceivedListener()
                                                          {
                                                              @Override
                                                              public void onReferralDataReceived(List<Map<String, String>> list)
                                                              {
                                                                  JSONArray resultArray = new JSONArray();

                                                                  for(int i = 0; i < list.size(); i++)
                                                                  {
                                                                      Map<String, String> entries = list.get(i);
                                                                      JSONObject obj = new JSONObject();
                                                                      for(Map.Entry<String, String> entry : entries.entrySet())
                                                                      {
                                                                          try
                                                                          {
                                                                              obj.put(entry.getKey(), entry.getValue());
                                                                          }
                                                                          catch(Exception e)
                                                                          {
                                                                          }
                                                                      }

                                                                      resultArray.put(obj);
                                                                  }

                                                                  PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, resultArray);
                                                                  pluginResult.setKeepCallback(true);
                                                                  callbackContext.sendPluginResult(pluginResult);
                                                              }
                                                          }
        );
    }


    private void setOnUserAvatarClickHandler(final CallbackContext callbackContext) {
        getSocialImpl().setOnUserAvatarClickHandler(
                new GetSocial.OnUserAvatarClickHandler()
                {
                    @Override
                    public boolean onUserAvatarClick(User user, int source)
                    {
                            JSONObject object = new JSONObject();
                            try {
                                object.put("user", user.serialize());
                                object.put("source", source);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, object);
                            pluginResult.setKeepCallback(true);
                            callbackContext.sendPluginResult(pluginResult);
                            return true; // event consumed
                    }
                }
        );
    }

    private void setOnAppAvatarClickHandler(final CallbackContext callbackContext) {
        getSocialImpl().setOnAppAvatarClickHandler(
                new GetSocial.OnAppAvatarClickHandler() {
                    @Override
                    public boolean onAppAvatarClick() {
                            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
                            pluginResult.setKeepCallback(true);
                            callbackContext.sendPluginResult(pluginResult);
                            return true; // event consumed
                    }
                }
        );
    }

    private void setOnActivityActionClickListener(final CallbackContext callbackContext) {
        getSocialImpl().setOnActivityActionClickListener(
                new GetSocial.OnActivityActionClickListener() {
                    @Override
                    public void onActivityActionClick(String action) {
                            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, action);
                            pluginResult.setKeepCallback(true);
                            callbackContext.sendPluginResult(pluginResult);
                    }
                }
        );
    }

    private void setOnInviteButtonClickListener(final CallbackContext callbackContext) {
        getSocialImpl().setOnInviteButtonClickListener(
                new GetSocial.OnInviteButtonClickListener() {
                    @Override
                    public boolean onInviteButtonClick() {
                            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
                            pluginResult.setKeepCallback(true);
                            callbackContext.sendPluginResult(pluginResult);
                            return true; // event consumed
                    }
                }
        );
    }

    private void setOnActionPerformListener(final CallbackContext callbackContext) {
        getSocialImpl().setOnActionPerformListener(
                new GetSocial.OnActionPerformListener() {
                    @Override
                    public void onActionPerform(GetSocial.Action action, final ActionFinalizer actionFinalizer) {
                        GetSocialCordova.actionFinalizer.put(actionFinalizer.hashCode(), actionFinalizer);
                        JSONObject object = new JSONObject();
                        try {
                            object.put("action", action);
                            object.put("actionFinalizerHash", actionFinalizer.hashCode());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, object);
                        pluginResult.setKeepCallback(true);
                        callbackContext.sendPluginResult(pluginResult);
                    }
                }
        );
    }

    private void finalizeAction(final int actionFinalizerHash, final boolean value, final CallbackContext callbackContext) {
        final GetSocial.OnActionPerformListener.ActionFinalizer actionFinalizer = GetSocialCordova.actionFinalizer.get(actionFinalizerHash);
        if(actionFinalizer != null) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    actionFinalizer.finalize(value);
                    GetSocialCordova.actionFinalizer.remove(actionFinalizerHash);
                    callbackContext.success();
                }
            });
        } else {
            callbackContext.error("Not found ActionFinalizer");
        }
    }

    private String[] getSupportedInviteProviders() {
        return getSocialImpl().getSupportedInviteProviders();
    }
    private boolean inviteFriendsUsingProvider(JSONObject option) {
        if(option == null)
            return false;

        String provider = option.optString("provider");
        if(provider.isEmpty())
            return false;

        String subject = option.optString("subject");
        if(subject.isEmpty())
            subject=null;

        String text = option.optString("text");
        if(text.isEmpty())
            text=null;

        Bitmap image = null;
        String imagePath = option.optString("imagePath");
        if(imagePath != null){
            image = loadImage(imagePath);
        }

        Map<String,String> referralData = null;
        JSONArray referralsArray = option.optJSONArray("referrals");
        if(referralsArray != null) {
            referralData = new HashMap<String, String>();
            for(int i=0; i< referralsArray.length(); i++) {
                JSONObject obj = referralsArray.optJSONObject(0);
                if(obj != null) {
                    Iterator<String> keysItr = obj.keys();
                    while(keysItr.hasNext()) {
                        String key = keysItr.next();
                        String value = obj.optString(key);

                        referralData.put(key, value);
                    }
                }
            }
        }

        getSocialImpl().inviteFriendsUsingProvider(provider, subject, text, image, referralData);

        return true;
    }

    private void registerPlugin(JSONObject pluginOptions, CallbackContext callbackContext) {
        boolean isAvailableForDevice = pluginOptions.optBoolean("isAvailableForDevice");
        String provider = pluginOptions.optString("provider");

        GetSocialPluginProxy getSocialPluginProxy = new GetSocialPluginProxy(callbackContext, isAvailableForDevice);
        getSocialImpl().registerPlugin(provider, getSocialPluginProxy);

        if(GetSocialCordova.registeredPlugins == null)
            GetSocialCordova.registeredPlugins = new HashMap<String, GetSocialPluginProxy>();

        registeredPlugins.put(callbackContext.getCallbackId(), getSocialPluginProxy);

        getSocialPluginProxy.initCallbackId(callbackContext.getCallbackId());
    }

    private boolean closeViewBuilder(){
        cordova.getActivity().runOnUiThread(new Runnable()
                                            {
                                                @Override
                                                public void run()
                                                {
                                                    getSocialImpl().handleBackButtonPressed();
                                                }
                                            }
        );
        return true;
    }

    private boolean createSmartInviteView(JSONObject option) {
        if(option == null)
            return false;

        SmartInviteViewBuilder smartInviteViewBuilder = getSocialImpl().createSmartInviteView();

        String subject = option.optString("subject");
        if(!subject.isEmpty())
            smartInviteViewBuilder.setSubject(subject);

        String text = option.optString("text");
        if(!text.isEmpty())
            smartInviteViewBuilder.setText(text);

        String title = option.optString("title");
        if(!title.isEmpty())
            smartInviteViewBuilder.setTitle(title);

        String imagePath = option.optString("imagePath");
        if(!imagePath.isEmpty()){
            Bitmap bitmap = loadImage(imagePath);
            if(bitmap != null){
                String imageUri = storeImageInAssetsProvider(bitmap);
                smartInviteViewBuilder.setImageUrl(imageUri);
            }
        }
        Map<String,String> referralData = getMapFromJSONArray(option.optJSONArray("referralData"));
        if(referralData != null)
            smartInviteViewBuilder.setReferralData(referralData);

        smartInviteViewBuilder.show();

        return true;
    }

    private Bitmap loadImage(String imagePath){
        Bitmap bitmap = null;
        try{
            // remove "/" from beginning if there is any
            if(imagePath.startsWith("/")){
                imagePath = imagePath.substring(1);
            }
            InputStream is = cordova.getActivity().getAssets().open(imagePath);
            bitmap = BitmapFactory.decodeStream(is);
            if(is != null){
                is.close();
            }
        }catch(Exception e){
            Log.e(TAG, "Could not load image.",e);
        }
        return bitmap;
    }

    private String storeImageInAssetsProvider(Bitmap bitmap){
        Uri bitmapURI = Utilities.getUriForBitmap(cordova.getActivity().getApplicationContext(), bitmap);
        return bitmapURI.toString();
    }

    private Map<String, String> getMapFromJSONArray(JSONArray array) {
        Map<String,String> referralData = null;
        if(array != null) {
            referralData = new HashMap<String, String>();
            for(int i=0; i< array.length(); i++) {
                JSONObject obj = array.optJSONObject(0);
                if(obj != null) {
                    Iterator<String> keysItr = obj.keys();
                    while(keysItr.hasNext()) {
                        String key = keysItr.next();
                        String value = obj.optString(key);

                        referralData.put(key, value);
                    }
                }
            }
        }

        return referralData;
    }

    private CurrentUser getCurrentUser() {
        return getSocialImpl().getCurrentUser();
    }

    private boolean createActivitiesView(JSONObject option) {
        String group = option.optString("group");
        ArrayList<String> tags = new ArrayList<String>();
        try {
            JSONArray jsonTags = option.optJSONArray("tags");
            if (jsonTags != null) {
                int len = jsonTags.length();
                for (int i=0;i<len;i++){
                    tags.add(jsonTags.get(i).toString());
                }
            }
        } catch (Exception e) {

        }


        ActivitiesViewBuilder activitiesViewBuilder = null;
        if(group.isEmpty()) {
            activitiesViewBuilder = getSocialImpl().createActivitiesView();
        } else {
            activitiesViewBuilder = getSocialImpl().createActivitiesView(group, tags);
        }

        activitiesViewBuilder.show();

        return true;
    }

    private boolean postActivity(JSONObject option, final CallbackContext callbackContext) {
        String text = option.optString("text", null);

        byte[] image = null;
        String imagePath = option.optString("imagePath");
        if(!imagePath.isEmpty()){
            Bitmap bitmap = loadImage(imagePath);
            if(bitmap != null){
                image = GetSocialUtil.getBytesOfBitmap(bitmap);
            }
        }

        String buttonText = option.optString("buttonText", null);
        String actionId = option.optString("actionId", null);
        String tags = option.optString("tags", null);

        getSocialImpl().postActivity(text, image, buttonText, actionId, tags, new GetSocial.OperationObserver() {
            @Override
            public void onSuccess(String s) {
                callbackContext.success(s);
            }

            @Override
            public void onFailure(String s) {
                callbackContext.error(s);
            }
        });

        return true;
    }

    private void createNotificationsView(JSONObject option) {
        NotificationsViewBuilder notificationViewBuilder = getSocialImpl().createNotificationsView();

            String title = option.optString("title");
            if (!title.isEmpty())
                notificationViewBuilder.setTitle(title);


        notificationViewBuilder.show();
    }

    private void setOnUnreadNotificationsCountChangeListener(final CallbackContext callbackContext) {
        getSocialImpl().setOnUnreadNotificationsCountChangedListener(new GetSocial.OnUnreadNotificationsCountChangedListener() {
            @Override
            public void onUnreadNotificationsCountChanged(int i) {
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, i);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        });
    }

    private void createUserListView(JSONObject option, final CallbackContext callbackContext) {
        UserListViewBuilder userListViewBuilder = getSocialImpl().createUserListView(new UserListViewBuilder.UserListObserver() {

            private JSONObject getReturnedData(String serializedUser, boolean isCancel) {
                JSONObject returnedData = new JSONObject();
                try {
                    returnedData.putOpt("serializedUser", serializedUser);
                    returnedData.put("isCancel", isCancel);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return returnedData;
            }

            @Override
            public void onUserSelected(User user) {
                callbackContext.success(getReturnedData(user.serialize(), false));
                Log.d(TAG,"Selected user: " + user.getDisplayName());
            }

            @Override
            public void onCancel() {
                callbackContext.success(getReturnedData(null, true));
                Log.d(TAG, "User selection cancelled");
            }
        });

        String title = option.optString("title");
        if (!title.isEmpty())
            userListViewBuilder.setTitle(title);

        userListViewBuilder.show();
    }

    private void getLeaderboard(String leaderboard, final CallbackContext callbackContext) {
        getSocialImpl().getLeaderboard(
                leaderboard,
                new GetSocial.OnOperationResultListener<Leaderboard>()
                {
                    @Override
                    public void onSuccess(Leaderboard leaderboard)
                    {
                        callbackContext.success(GetSocialUtil.serializeLeaderbord(leaderboard));
                    }

                    @Override
                    public void onFailure(Exception exception)
                    {
                        callbackContext.error(exception.getMessage());
                        Log.d(TAG, exception.getMessage());
                    }
                }
        );
    }

    private void getLeaderboardsArray( JSONArray leaderboards, final CallbackContext callbackContext) {

        final ArrayList<String> leaderboardsAsString = new ArrayList<String>();
        for(int i=0; i < leaderboards.length(); i++) {
            try {
                leaderboardsAsString.add(leaderboards.getString(i));
            }catch (JSONException err) {

            }
        }
        getSocialImpl().getLeaderboards(
                leaderboardsAsString,
                new GetSocial.OnOperationResultListener<List<Leaderboard>>()
                {
                    @Override
                    public void onSuccess(List<Leaderboard> leaderboards)
                    {
                        JSONArray leaderboardsJSONArray = new JSONArray();
                        for(Leaderboard leaderboard : leaderboards)
                        {
                            leaderboardsJSONArray.put(GetSocialUtil.serializeLeaderbord(leaderboard));
                        }

                        callbackContext.success(leaderboardsJSONArray);
                    }

                    @Override
                    public void onFailure(Exception exception)
                    {
                        callbackContext.error(exception.getMessage());
                    }
                });
    }

    private void getLeaderboardsInterval(int start, int end, final CallbackContext callbackContext) {
        getSocialImpl().getLeaderboards(
                start, end,
                new GetSocial.OnOperationResultListener<List<Leaderboard>>()
                {
                    @Override
                    public void onSuccess(List<Leaderboard> leaderboards)
                    {
                        JSONArray leaderboardsJSONArray = new JSONArray();
                        for(Leaderboard leaderboard : leaderboards)
                        {
                            leaderboardsJSONArray.put(GetSocialUtil.serializeLeaderbord(leaderboard));
                        }

                        callbackContext.success(leaderboardsJSONArray);
                    }

                    @Override
                    public void onFailure(Exception exception)
                    {
                        callbackContext.error(exception.getMessage());
                    }
                });
    }

    private void getLeaderboardScores(JSONObject object, final CallbackContext callbackContext) {
        String leaderboard = object.optString("id");
        int start = object.optInt("start");
        int end = object.optInt("end");
        int type = object.optInt("type");

        getSocialImpl().getLeaderboardScores(leaderboard, start, end, type,
                new GetSocial.OnOperationResultListener<List<LeaderboardScore>>()
                {
                    @Override
                    public void onSuccess(List<LeaderboardScore> leaderboardScores)
                    {
                        JSONArray leaderboardsScoreJSONArray = new JSONArray();
                        for(LeaderboardScore leaderboardScore : leaderboardScores)
                        {
                            leaderboardsScoreJSONArray.put(GetSocialUtil.serializeLeaderboardScore(leaderboardScore));
                        }

                        callbackContext.success(leaderboardsScoreJSONArray);
                    }

                    @Override
                    public void onFailure(Exception exception)
                    {
                        callbackContext.error(exception.getLocalizedMessage());
                        Log.e(TAG,exception.getMessage());
                    }
                }
        );
    }

    private void submitLeaderboardScore(JSONObject object, final CallbackContext callbackContext) {
        final int value = object.optInt("value");
        final String leaderboardId = object.optString("id");
        getSocialImpl().submitLeaderboardScore(leaderboardId, value,
                new GetSocial.OnOperationResultListener<Integer>()
                {
                    @Override
                    public void onSuccess(Integer newRank)
                    {
                        callbackContext.success(newRank);
                        Log.d(TAG, String.format("Submitted score %s to LB '%s', new rank: %s", value, leaderboardId, newRank));
                    }

                    @Override
                    public void onFailure(Exception exception)
                    {
                        callbackContext.success(exception.getLocalizedMessage());
                        Log.d(TAG, String.format("Failed to submit score %s to LB '%s', error: %s", value, leaderboardId, exception.getMessage()));
                    }
                }
        );
    }

    private void cloudSaveData(String data, final CallbackContext callbackContext)
    {
        getSocialImpl().save(data);
        callbackContext.success();

    }

    private void getCloudSaveData(final CallbackContext callbackContext)
    {
        getSocialImpl().getLastSave(
                new GetSocial.OperationObserver()
                {
                    @Override
                    public void onSuccess(String data)
                    {
                        callbackContext.success(data);
                        Log.d(TAG,"Loaded data: " + data);
                    }

                    @Override
                    public void onFailure(String errorMessage)
                    {
                        callbackContext.error(errorMessage);
                        Log.d(TAG,errorMessage);
                    }
                }
        );
    }

    private void setLanguage(String lang, final CallbackContext callbackContext) {
        getSocialImpl().setLanguage(lang);
        callbackContext.success();
    }

    private void getLanguage(final CallbackContext callbackContext) {
        callbackContext.success(getSocialImpl().getLanguage());
    }

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        if(action.equalsIgnoreCase(REGISTER_PLUGIN_METHOD)) {
            if(data.length() != 1)
                return false;

            registerPlugin(data.getJSONObject(0), callbackContext);
            return true;
        }

        if(action.equals(CREATE_SMART_INVITE_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }
            return createSmartInviteView(data.getJSONObject(0));
        }

        if(action.equals(INVITE_FRIENDS_USING_PROVIDER_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            return inviteFriendsUsingProvider(data.getJSONObject(0));
        }

        if(action.equals(GET_SUPPORTED_INVITE_PROVIDERS_METHOD)) {
            JSONArray resultArray = new JSONArray();
            for (String item:getSupportedInviteProviders()) {
                resultArray.put(item);
            }
            callbackContext.success(resultArray);

            return true;
        }

        if(action.equals(SET_ON_REFERAL_DATA_RECEIVED_LISTENER_METHOD)) {
            setOnReferralDataReceivedListener(callbackContext);

            return true;
        }

        if(action.equals(SET_ON_INVITE_FRIENDS_LISTENER_METHOD)) {
            setOnInviteFriendsListener(callbackContext);

            return true;
        }

        if(action.equals(INIT_METHOD)) {
            final String key = data.getString(0);
            init(key, callbackContext);

            return true;
        }

        if(action.equals(IS_INITIALIZED_METHOD)) {
            callbackContext.success(isInitialized() ? 1 : 0);

            return true;
        }

        if(action.equals(GET_VERSION_METHOD)) {
            callbackContext.success(getVersion());

            return true;
        }

        if(action.equals(GET_API_VERSION_METHOD)) {
            callbackContext.success(getApiVersion());

            return true;
        }

        if(action.equals(GET_ENVIROMENT_METHOD)) {
            callbackContext.success(getEnvironment());

            return true;
        }

        if(action.equals(GET_CONFIGURATION_VERSION_METHOD)) {
            // Need to check. Crash on click
            Configuration config = getConfiguration();
            callbackContext.success("");

            return true;
        }

        if(action.equals(CLOSE_SMART_INVITE_VIEW_METHOD)) {
            return closeViewBuilder();
        }

        if(action.equals(GET_CURRENT_USER)) {
            CurrentUser user = getCurrentUser();
            callbackContext.success(user.serialize());

            return true;
        }

        if(action.equals(CREATE_ACTIVITIES_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }
            return createActivitiesView(data.getJSONObject(0));
        }

        if(action.equals(CLOSE_ACTIVITIES_VIEW_METHOD)) {
            return closeViewBuilder();
        }

        if(action.equals(POST_ACTIVITY_METHOD)) {
            if(data.length() == 0) {
                return false;
            }
            return postActivity(data.getJSONObject(0), callbackContext);
        }

        if(action.equals(CREATE_NOTIFICATIONS_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            createNotificationsView(data.getJSONObject(0));
            return true;

        }
        if(action.equals(SET_ON_UNREAD_NOTIFICATIONS_COUNT_LISTENER_METHOD)) {
            setOnUnreadNotificationsCountChangeListener(callbackContext);
        }
        if(action.equals(CLOSE_NOTIFICATIONS_VIEW_METHOD)) {
            return closeViewBuilder();
        }
        if(action.equals(CREATE_USER_LIST_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            createUserListView(data.getJSONObject(0), callbackContext);
            return true;
        }
        if(action.equals(CLOSE_USER_LIST_VIEW_METHOD)) {
            closeViewBuilder();
        }
        if(action.equals(GET_LEADRBOARD_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            getLeaderboard(data.getString(0), callbackContext);
            return true;
        }

        if(action.equals(GET_LEADRBOARDS_ARRAY_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            getLeaderboardsArray(data.getJSONArray(0), callbackContext);
            return true;
        }

        if(action.equals(GET_LEADRBOARDS_INTERVAL_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            getLeaderboardsInterval(data.getInt(0), data.getInt(1), callbackContext);
            return true;
        }

        if(action.equals(GET_LEADRBOARDS_SCORES_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            getLeaderboardScores(data.getJSONObject(0), callbackContext);
            return true;
        }

        if(action.equals(SUBMIT_LEADERBOARD_SCORE_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            submitLeaderboardScore(data.getJSONObject(0), callbackContext);
            return true;
        }
        if(action.equals(SUBMIT_CLOUD_SAVE_VIEW_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            cloudSaveData(data.getString(0), callbackContext);
            return true;
        }
        if(action.equals(SUBMIT_GET_CLOUD_SAVE_VIEW_METHOD)) {
            getCloudSaveData(callbackContext);
            return true;
        }
        if(action.equals(SET_LANGUAGE_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            setLanguage(data.getString(0), callbackContext);
            return true;
        }
        if(action.equals(GET_LANGUAGE_METHOD)) {
            getLanguage(callbackContext);
            return true;
        }
        if(action.equals(SET_ON_USER_AVATAR_CLICK_HANDLER_METHOD)) {
            if (data.length() == 0) {
                return false;
            }

            setOnUserAvatarClickHandler(callbackContext);
            return true;
        }
        if(action.equals(SET_ON_APP_AVATAR_CLICK_HANDLER_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            setOnAppAvatarClickHandler(callbackContext);
            return true;
        }
        if(action.equals(SET_ON_ACTIVITY_ACTION_CLICK_LISTENER_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            setOnActivityActionClickListener(callbackContext);
            return true;
        }
        if(action.equals(SET_ON_INVITE_BUTTON_CLICK_LISTENER_METHOD)) {
            if(data.length() == 0) {
                return false;
            }

            setOnInviteButtonClickListener(callbackContext);
            return true;
        }
        if(action.equals(SET_ON_ACTION_PERFORM_LISTENER_METHOD)) {
            setOnActionPerformListener(callbackContext);
            return true;
        }
        if(action.equals(FINALIZE_ACTION_METHOD)) {
            if(data.length() != 2) {
                return false;
            }

            finalizeAction(data.getInt(0), data.getBoolean(1), callbackContext);
            return true;
        }



        return false;
    }
}
