/*
 *    	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.text.TextUtils;
import android.util.Log;

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

import im.getsocial.sdk.core.AddUserIdentityObserver;
import im.getsocial.sdk.core.CurrentUser;
import im.getsocial.sdk.core.GetSocial;
import im.getsocial.sdk.core.User;
import im.getsocial.sdk.core.UserIdentity;

/**
 * Created by adventis on 4/15/16.
 */
public class GetSocialCurrentUser extends CordovaPlugin {
    private final String TAG = "GetSocialCordova_Plugin";

    private GetSocial mGetSocialImpl;

    public static AddUserIdentityObserver.UserIdentityResolver userIdentityResolver;

    private final String RESOLVE_USER_IDENTITY_CONFLICT = "resolveUserIdentityConflict";
    private final String SET_DISPLAY_NAME_METHOD = "setDisplayName";
    private final String SET_AVATAR_URL_METHOD = "setAvatarUrl";
    private final String ADD_FB_USER_IDENTITY = "addFbUserIdentity";
    private final String ADD_GOOGLE_PLUS_USER_IDENTITY = "addGooglePlusUserIdentity";
    private final String ADD_GOOGLE_PLAY_USER_IDENTITY = "addGooglePlayUserIdentity";
    private final String ADD_USER_IDENTITY = "addUserIdentity";
    private final String REMOVE_FB_USER_IDENTITY = "removeFbUserIdentity";
    private final String REMOVE_GOOGLE_PLUS_USER_IDENTITY = "removeGooglePlusUserIdentity";
    private final String REMOVE_GOOGLE_PLAY_USER_IDENTITY = "removeGooglePlayUserIdentity";
    private final String REMOVE_USER_IDENTITY = "removeUserIdentity";
    private final String RESET = "reset";

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

        return this.mGetSocialImpl;
    }

    private void resolveUserIdentityConflict(String resolution, final CallbackContext callbackContext) {
        if(GetSocialCurrentUser.userIdentityResolver != null) {
            if(resolution.equalsIgnoreCase("remote")) {
                GetSocialCurrentUser.userIdentityResolver.resolve(AddUserIdentityObserver.AddIdentityConflictResolutionStrategy.REMOTE);
                callbackContext.success();
            } else if(resolution.equalsIgnoreCase("current")) {
                GetSocialCurrentUser.userIdentityResolver.resolve(AddUserIdentityObserver.AddIdentityConflictResolutionStrategy.CURRENT);
                callbackContext.success();
            }
        }

        callbackContext.error("Not found user identity conflicts");
    }

    private void setDisplayName(final String name, final CallbackContext callbackContext) {

        getSocialImpl().getCurrentUser().setDisplayName(name, new CurrentUser.UpdateUserInfoObserver() {
            @Override
            public void onComplete()
            {
                Log.d(TAG, "User display name was changed to" + name);
                callbackContext.success(getSocialImpl().getCurrentUser().serialize());
            }

            @Override
            public void onError(Exception e)
            {
                Log.d(TAG, "Cannot change display name. Reason " + e.getMessage());
                callbackContext.error(e.getMessage());
            }
        });
    }

    private void setAvatarUrl(final String avatarUrl, final CallbackContext callbackContext) {
        getSocialImpl().getCurrentUser().setAvatarUrl(avatarUrl, new CurrentUser.UpdateUserInfoObserver() {
            @Override
            public void onComplete()
            {
                Log.d(TAG, "User avatar was changed to " + avatarUrl);
                callbackContext.success(getSocialImpl().getCurrentUser().serialize());
            }

            @Override
            public void onError(Exception e)
            {
                Log.d(TAG, "Cannot change avatar. Reason " + e.getMessage());
                callbackContext.error(e.getMessage());
            }
        });
    }

    private void addFbUserIdentity(String token, final CallbackContext callbackContext)
    {
                GetSocialCurrentUser.userIdentityResolver = null;

                UserIdentity fbIdentity = UserIdentity.createFacebookIdentity(token);
                getSocialImpl().getCurrentUser().addUserIdentity(
                        fbIdentity,
                        new AddUserIdentityObserver()
                        {
                            private JSONObject getReturnedData(boolean isConflict, int resolveSatus) {
                                JSONObject returnedData = new JSONObject();
                                try {
                                    returnedData.putOpt("serializedUser", getSocialImpl().getCurrentUser().serialize());
                                    returnedData.put("isConflict", isConflict);
                                    returnedData.put("resolveStatus", resolveSatus);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                return returnedData;
                            }

                            @Override
                            public void onComplete(AddIdentityResult addIdentityResult)
                            {
                                //check if we continue with a user that has facebook identity
                                if(addIdentityResult==AddIdentityResult.CONFLICT_WAS_RESOLVED_WITH_CURRENT)
                                {
                                    Log.d(TAG, "Facebook identity is not added");
                                }
                                else
                                {
                                    Log.d(TAG, "Adding Facebook identity finished successfully");
                                }
                                callbackContext.success(getReturnedData(false, addIdentityResult.getIntValue()));
                            }

                            @Override
                            public void onError(Exception error)
                            {
                                Log.d(TAG, "Failed to add Facebook user identity, error: " + error.getMessage());
                                callbackContext.error(error.getMessage());
                            }

                            @Override
                            public void onConflict(User currentUser, User remoteUser, UserIdentityResolver resolver)
                            {
                                GetSocialCurrentUser.userIdentityResolver = resolver;

                                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, getReturnedData(true, 0));
                                pluginResult.setKeepCallback(true);
                                callbackContext.sendPluginResult(pluginResult);
                            }
                        }
                );
        //LoginManager.getInstance().logInWithReadPermissions(cordova.getActivity(), FACEBOOK_PERMISSIONS);
    }

    private void addGooglePlusUserIdentity(String token, final CallbackContext callbackContext)
    {
        GetSocialCurrentUser.userIdentityResolver = null;

        UserIdentity googleIdentity = UserIdentity.create(UserIdentity.PROVIDER_GOOGLEPLUS, token);
        GetSocial.getInstance().getCurrentUser().addUserIdentity(googleIdentity, new AddUserIdentityObserver()
                {
                    private JSONObject getReturnedData(boolean isConflict, int resolveSatus) {
                        JSONObject returnedData = new JSONObject();
                        try {
                            returnedData.putOpt("serializedUser", getSocialImpl().getCurrentUser().serialize());
                            returnedData.put("isConflict", isConflict);
                            returnedData.put("resolveStatus", resolveSatus);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return returnedData;
                    }

                    @Override
                    public void onComplete(AddIdentityResult addIdentityResult)
                    {

                        if(addIdentityResult==AddIdentityResult.CONFLICT_WAS_RESOLVED_WITH_CURRENT)
                        {
                            Log.d(TAG,"Google+ identity is not added");
                        }
                        else
                        {
                            Log.d(TAG,"Adding Google+ finished successfully");
                        }
                        callbackContext.success(getReturnedData(false, addIdentityResult.getIntValue()));
                    }

                    @Override
                    public void onError(Exception error)
                    {
                        Log.d(TAG,"Failed to add Google+ user identity, error: " + error.getMessage());
                        callbackContext.error(error.getMessage());
                    }

                    @Override
                    public void onConflict(User currentUser, User remoteUser, UserIdentityResolver resolver)
                    {
                        GetSocialCurrentUser.userIdentityResolver = resolver;

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

    private void addGooglePlayUserIdentity(String token, final CallbackContext callbackContext)
    {
        GetSocialCurrentUser.userIdentityResolver = null;

        UserIdentity googleIdentity = UserIdentity.create(UserIdentity.PROVIDER_GOOGLEPLAY, token);
        GetSocial.getInstance().getCurrentUser().addUserIdentity(googleIdentity, new AddUserIdentityObserver()
                {
                    private JSONObject getReturnedData(boolean isConflict, int resolveSatus) {
                        JSONObject returnedData = new JSONObject();
                        try {
                            returnedData.putOpt("serializedUser", getSocialImpl().getCurrentUser().serialize());
                            returnedData.put("isConflict", isConflict);
                            returnedData.put("resolveStatus", resolveSatus);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return returnedData;
                    }

                    @Override
                    public void onComplete(AddIdentityResult addIdentityResult)
                    {

                        if(addIdentityResult==AddIdentityResult.CONFLICT_WAS_RESOLVED_WITH_CURRENT)
                        {
                            Log.d(TAG, "GooglePlay identity is not added");
                        }
                        else
                        {
                            Log.d(TAG,"Adding GooglePlay finished successfully");
                        }
                        callbackContext.success(getReturnedData(false, addIdentityResult.getIntValue()));
                    }

                    @Override
                    public void onError(Exception error)
                    {
                        Log.d(TAG, "Failed to add Google Play user identity, error: " + error.getMessage());
                        callbackContext.error(error.getMessage());
                    }

                    @Override
                    public void onConflict(User currentUser, User remoteUser, UserIdentityResolver resolver)
                    {
                        GetSocialCurrentUser.userIdentityResolver = resolver;

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

    private void addUserIdentity(String userId, String token, final CallbackContext callbackContext)
    {
        if(TextUtils.isEmpty(userId) || TextUtils.isEmpty(token))
        {
            Log.d(TAG, "Failed to add User Identity, User Id and Token fields can't be empty");
            callbackContext.error("Failed to add User Identity, User Id and Token fields can't be empty");
        }
        else
        {
            GetSocialCurrentUser.userIdentityResolver = null;

            UserIdentity identity = UserIdentity.create("Custom", userId, token);
            getSocialImpl().getCurrentUser().addUserIdentity(
                    identity,
                    new AddUserIdentityObserver()
                    {
                        private JSONObject getReturnedData(boolean isConflict, int resolveSatus) {
                            JSONObject returnedData = new JSONObject();
                            try {
                                returnedData.putOpt("serializedUser", getSocialImpl().getCurrentUser().serialize());
                                returnedData.put("isConflict", isConflict);
                                returnedData.put("resolveStatus", resolveSatus);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            return returnedData;
                        }

                        @Override
                        public void onComplete(AddIdentityResult addIdentityResult)
                        {
                            if(addIdentityResult==AddIdentityResult.CONFLICT_WAS_RESOLVED_WITH_CURRENT)
                            {
                                Log.d(TAG, "'custom identity' is not added");
                            }
                            else
                            {
                                Log.d(TAG, "Adding 'custom identity' finished successfully");
                            }
                            callbackContext.success(getReturnedData(false, addIdentityResult.getIntValue()));
                        }

                        @Override
                        public void onError(Exception error)
                        {
                            Log.d(TAG, "Failed to add user identity 'custom', error: " + error.getMessage());
                            callbackContext.error(error.getMessage());
                        }

                        @Override
                        public void onConflict(User currentUser, User remoteUser, UserIdentityResolver resolver)
                        {
                            GetSocialCurrentUser.userIdentityResolver = resolver;

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

    private void removeFbUserIdentity(final CallbackContext callbackContext)
    {
        getSocialImpl().getCurrentUser().removeUserIdentity(UserIdentity.PROVIDER_FACEBOOK, new CurrentUser.UpdateUserInfoObserver() {
            @Override
            public void onComplete()
            {
                Log.d(TAG, "Successfully removed Facebook user identity");
                callbackContext.success(getSocialImpl().getCurrentUser().serialize());
            }

            @Override
            public void onError(Exception e)
            {
                Log.d(TAG, "Failed to remove Facebook user identity, error: " + e.getMessage());
                callbackContext.error(e.getMessage());
            }
        });
    }

    private void removeGooglePlusUserIdentity(final CallbackContext callbackContext)
    {
        getSocialImpl().getCurrentUser().removeUserIdentity(UserIdentity.PROVIDER_GOOGLEPLUS, new CurrentUser.UpdateUserInfoObserver() {
            @Override
            public void onComplete()
            {
                Log.d(TAG, "Successfully removed Google+ user identity");
                callbackContext.success(getSocialImpl().getCurrentUser().serialize());
            }

            @Override
            public void onError(Exception e)
            {
                Log.d(TAG, "Failed to remove Google+ user identity, error: " + e.getMessage());
                callbackContext.error(e.getMessage());
            }
        });
    }

    private void removeGooglePlayUserIdentity(final CallbackContext callbackContext)
    {
        getSocialImpl().getCurrentUser().removeUserIdentity(UserIdentity.PROVIDER_GOOGLEPLAY, new CurrentUser.UpdateUserInfoObserver() {
            @Override
            public void onComplete()
            {
                Log.d(TAG, "Successfully removed Google Play user identity");
                callbackContext.success(getSocialImpl().getCurrentUser().serialize());
            }

            @Override
            public void onError(Exception e)
            {
                Log.d(TAG, "Failed to remove Google Play user identity, error: " + e.getMessage());
                callbackContext.error(e.getMessage());
            }
        });
    }

    private void removeUserIdentity(final String providerId, final CallbackContext callbackContext)
    {
        getSocialImpl().getCurrentUser().removeUserIdentity(providerId, new CurrentUser.UpdateUserInfoObserver() {
            @Override
            public void onComplete()
            {
                Log.d(TAG, String.format("Successfully removed user identity '%s'", providerId));
                callbackContext.success(getSocialImpl().getCurrentUser().serialize());
            }

            @Override
            public void onError(Exception e)
            {
                Log.d(TAG, String.format("Failed to remove user identity '%s', error: %s", providerId, e.getMessage()));
                callbackContext.error(e.getMessage());
            }
        });
    }

    private void resetUser(final  CallbackContext callbackContext) {
        getSocialImpl().getCurrentUser().reset(new CurrentUser.UpdateUserInfoObserver() {
            @Override
            public void onComplete()
            {
                Log.d(TAG, "Successfully reseted");
                callbackContext.success(getSocialImpl().getCurrentUser().serialize());
                Log.d(TAG,"A");
            }

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

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        if(action.equalsIgnoreCase(RESOLVE_USER_IDENTITY_CONFLICT)) {
            if(args.length() != 1)
                return false;

            resolveUserIdentityConflict(args.optString(0), callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(SET_DISPLAY_NAME_METHOD)) {
            if(args.length() != 1)
                return false;

            setDisplayName(args.optString(0), callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(SET_AVATAR_URL_METHOD)) {
            if(args.length() != 1)
                return false;

            setAvatarUrl(args.optString(0), callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(ADD_FB_USER_IDENTITY)) {
            if(args.length() != 1)
                return false;

            addFbUserIdentity(args.optString(0), callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(ADD_GOOGLE_PLUS_USER_IDENTITY)) {
            if(args.length() != 1)
                return false;

            addGooglePlusUserIdentity(args.optString(0), callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(ADD_GOOGLE_PLAY_USER_IDENTITY)) {
            if(args.length() != 1)
                return false;

            addGooglePlayUserIdentity(args.optString(0), callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(ADD_USER_IDENTITY)) {
            if(args.length() != 2)
                return false;

            String userId = args.getString(0);
            String token = args.getString(1);

            addUserIdentity(userId,token,callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(REMOVE_FB_USER_IDENTITY)) {
            removeFbUserIdentity(callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(REMOVE_GOOGLE_PLAY_USER_IDENTITY)) {
            removeGooglePlayUserIdentity(callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(REMOVE_GOOGLE_PLUS_USER_IDENTITY)) {
            removeGooglePlusUserIdentity(callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(REMOVE_USER_IDENTITY)) {
            if(args.length() != 1)
                return false;

            String providerId = args.getString(0);
            removeUserIdentity(providerId, callbackContext);
            return true;
        }

        if(action.equalsIgnoreCase(RESET)) {
            resetUser(callbackContext);
            return true;
        }

        return false;
    }
}
