/*
 *    	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 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.chat.GetSocialChat;
import im.getsocial.sdk.chat.UI.builder.ChatListViewBuilder;
import im.getsocial.sdk.chat.UI.builder.ChatViewBuilder;
import im.getsocial.sdk.core.GetSocial;

/**
 * Created by adventis on 5/8/16.
 */
public class GetSocialChatCordova extends CordovaPlugin {

    private GetSocialChat mGetSocialChatImpl;

    private final String UNREAD_CONVERSATIONS_COUNT = "unreadConversationsCount";
    private final String IS_ENABLE = "isEnable";
    private final String SET_ON_UNREAD_CONVERSATIONS_COUNT_CHANGE_LISTENER = "setOnUnreadConversationsCountChangeListener";
    private final String CREATE_CHAT_VIEW = "createChatView";
    private final String CREATE_CHAT_LIST_VIEW = "createChatListView";
    private final String CLOSE_CHAT_VIEW = "closeChatView";

    private GetSocialChat getSocialChatImpl() {
        if(this.mGetSocialChatImpl == null) {
            this.mGetSocialChatImpl = GetSocialChat.getInstance();
        }

        return this.mGetSocialChatImpl;
    }

    private int getUnreadConversationsCount() {
        return getSocialChatImpl().getUnreadConversationsCount();
    }

    private boolean isEnable() {
        return getSocialChatImpl().isEnabled();
    }

    private void setOnUnreadConversationsCountChangeListener(final CallbackContext callbackContext) {
        getSocialChatImpl().setOnUnreadConversationsCountChangedListener(new GetSocialChat.OnUnreadConversationsCountChangedListener() {
            @Override
            public void onUnreadConversationsCountChanged(int i) {
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, i);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        });
    }

    private boolean createChatListView(JSONObject data) {
        ChatListViewBuilder globalChatListView = getSocialChatImpl().createChatListView();

        String title = data.optString("title");
        if(!title.isEmpty())
            globalChatListView.setTitle(title);

        globalChatListView.show();

        return true;
    }

    private boolean createChatView(JSONObject data) {
        ChatViewBuilder globalChatView = null;

        String roomName = data.optString("roomName");
        if(!roomName.isEmpty()) {
            globalChatView = getSocialChatImpl().createChatViewForRoomName(roomName);
        }

        String conversationId = data.optString("conversationId");
        if(!conversationId.isEmpty()) {
            globalChatView = getSocialChatImpl().createChatViewForConversationId(conversationId);
        }

        String userId = data.optString("userId");
        if(!userId.isEmpty()) {
            globalChatView = getSocialChatImpl().createChatViewForUserId(userId);
        }

        String providerId = data.optString("providerId");
        if(!userId.isEmpty() && !providerId.isEmpty()) {
            globalChatView = getSocialChatImpl().createChatViewForUserIdOnProvider(userId, providerId);
        }

        String title = data.optString("title");
        if(globalChatView != null) {
            if(!title.isEmpty())
                globalChatView.setTitle(title);

            globalChatView.show();

            return true;
        }

        return false;
    }

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

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        if(action.equalsIgnoreCase(UNREAD_CONVERSATIONS_COUNT)) {
            callbackContext.success(getUnreadConversationsCount());

            return true;
        }

        if(action.equalsIgnoreCase(IS_ENABLE)) {
            callbackContext.success(isEnable() ? 1 : 0);

            return true;
        }

        if(action.equalsIgnoreCase(SET_ON_UNREAD_CONVERSATIONS_COUNT_CHANGE_LISTENER)) {
            setOnUnreadConversationsCountChangeListener(callbackContext);

            return true;
        }

        if(action.equalsIgnoreCase(CREATE_CHAT_VIEW)) {
            if(data.length() == 0)
                return  false;

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

        if(action.equalsIgnoreCase(CREATE_CHAT_LIST_VIEW)) {
            if(data.length() == 0)
                return  false;

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

        if(action.equalsIgnoreCase(CLOSE_CHAT_VIEW)) {
            return closeViewBuilder();
        }

        return false;
    }
}
