/*
 * /////////////////////////////////////////////////////////////////////////////////
 * //
 * // Copyright <2015>-<2016> Avaya Inc. All Rights Reserved.
 * //
 * // Usage of this source is bound to the terms described
 * // in assets/Licence.txt
 * //
 * // Avaya - Confidential & Proprietary. Use pursuant to your signed agreement
 * // or Avaya Policy
 * //
 * /////////////////////////////////////////////////////////////////////////////
 */

package com.avaya.odonnell3.AndroidChatTemplate_2_3.UtilClasses;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.animation.*;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.R;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.activities.ChatActivity;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.activities.MainActivity;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.ChatMessage;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.classes.MessageParser;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.fragments.ChatActivityFragment;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.AgentIsTyping;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.CustomerParticipant;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewAgentFileTransfer;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewAutomationMessageNotification;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewCoBrowseNotification;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewMessageNotification;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.CloseConversationNotice;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.CloseConversationRequest;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.CustomerJsonWrapper;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewMessageAck;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewParticipant;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.PagePush;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.ParticipantLeave;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.Global;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.WebSocketService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class ChatActivityUtils extends Activity {

    private ChatActivity activity;
    private Timer timer;
    private Map<String, String> agentsMap = new HashMap<String, String>();

    public ChatActivityUtils(ChatActivity activity) {
        this.activity = activity;
    }

    public void hideChatWindow(View agentDialog, TextView chatBubble) {
        Log.v("Info", activity.activityName + "hideChatWindow()");
        agentDialog.setVisibility(View.GONE);
        chatBubble.setVisibility(View.GONE);
    }

    //remove customer input if chat is closed
    public void hideChatUI(ChatActivityFragment fragment) {
        Log.v("Info", activity.activityName + "hideChatUI()");
        fragment.getSendButton().setVisibility(View.GONE);
        fragment.getTextInputLayout().setVisibility(View.GONE);
    }

    public void showChatUI(ChatActivityFragment fragment) {
        Log.v("Info", activity.activityName + "showChatUI()");
        fragment.getSendButton().setVisibility(View.VISIBLE);
        fragment.getTextInputLayout().setVisibility(View.VISIBLE);

    }

    //sets the initial fragment in the given container
    public void setInitialFragment(Bundle savedInstanceState, int container) {
        Log.v("Info", activity.activityName + "setInitialFragment()");
        if (savedInstanceState == null) {
            Bundle b = new Bundle();
            String greeting = activity.waitIntent.getStringExtra("agentGreeting");
            b.putString("agentGreeting", greeting);
            activity.chatFragment.setArguments(b);
            activity.getFragmentManager().beginTransaction().add(container, activity.browseFragment).add(container, activity.chatFragment).hide(activity.browseFragment).commit();
        }
    }

    //send close request and wait for broadcast of notification
    public void sendCloseChatRequest() {
        Log.v("Info", activity.activityName + " sendCloseChatRequest()");
        CustomerJsonWrapper wrapper = new CustomerJsonWrapper("request");
        CloseConversationRequest request = new CloseConversationRequest();
        wrapper.setBody(request);
        String message = MessageParser.javaObjectToJson(wrapper);
        Log.v("Info", "connection on close: " + activity.wsClient.getConnection());
        try {
            activity.wsClient.send(message);
        } catch (Exception e) {

        }
    }

    //makes notification sound when app generates notification
    public void getNotificationSound() {
        Log.v("Info", activity.activityName + "getNotificationSound()");
        Vibrator vibe = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
        vibe.vibrate(500);
        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(activity, notification);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //close soft-Keyboard
    public void closeKeyboard() {
        Log.v("Info", activity.activityName + " closeKeyboard()");
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    //show the agent page-push message on the screen
    public void putAgentPagePush(PagePush pagePush) {
        Log.v("Info", activity.activityName + " putAgentPagePush()");
        ChatMessage cm = new ChatMessage();
        cm.setName(pagePush.getDisplayName());
        cm.setMessage(pagePush.getPagePushURL());
        cm.setTime(MessageParser.getTime(pagePush.getTimestamp()));
        cm.setSenderType(3);
        activity.chatFragment.showAgentMessage(cm);
    }
//TODO
    //carry out actions depending on which message has be received
    public void getWsMessageByType(String message) {
        Log.v("Info", activity.activityName + "  getWsMessageByType()");
        Log.v("***Message***",message);
        CustomerJsonWrapper wrapper;
        wrapper = MessageParser.jsonStringToJava(message);
        if (wrapper != null) {

            switch (wrapper.getBody().getClass().getSimpleName()) {
                case "AgentIsTyping":
                    putAgentIsTyping(wrapper);
                    break;
                case "NewMessageNotification":
                    putAgentMessage(wrapper);
                    break;
                case "PagePush":
                    getPagePushMessageType(wrapper);
                    break;
                case "CloseConversationNotice":
                    closeChat(wrapper);
                    break;
                case "ParticipantLeave":
                    putParticipantLeave(wrapper);
                    break;
                case "NewParticipant":
                    putParticipantJoin(wrapper);
                    activity.agentHasLeft  = false;
                    break;
                case "NewMessageAck":
                    getCustomerAck(wrapper);
                    break;
                case "RouteCancel":

                    Log.e("Error", "Route Cancel message Received");
                    Toast.makeText(activity,"A Chat is no longer available, please try again later",Toast.LENGTH_SHORT).show();
                    sendCloseChatRequest();
                    break;
                case "Pong":
                    break;
                case "NewAgentFileTransfer" :
                    //{"apiVersion":"1.0","type":"notification","body":{"agentName":"Agent","name":"new  2.txt",
                    // "mimeType":"text/plain","size":"370","uuid":"2ED77B9D-B0A2-4D93-A8C9-DB2FE138C5A6","workRequestId":"beLTLjFhTUWZOkJNAIAwWA","method":"newAgentFileTransfer"},"authToken":""}
                    putFileTransferMessage(wrapper);
                    break;
                case "NewCoBrowseNotification" :
                    notifyNewCoBrowseSessionKeyMessage(wrapper);
                    break;
                default:
                    Log.e("Error", "message type not recognised\n" + activity.inMessage);
                    break;
            }
        }
        else{
            Log.e("ChatActivityUtils ",": putAgentPagePush() Failed");
        }
    }

    private void putFileTransferMessage(CustomerJsonWrapper wrapper) {
        NewAgentFileTransfer fileTransfer = null;
        String transferUrl = "";
        try {
            fileTransfer = (NewAgentFileTransfer) wrapper.getBody();
            String uriTemp = Global.addressesMap.get("CustomerController");
            String uri = uriTemp.substring(uriTemp.lastIndexOf('/')+1);
            transferUrl = ((uriTemp.contains("wss")? "https://":"http://") + uri + "/services/customer/rest/attachment/" + fileTransfer.getUuid() + "?workRequestId="+fileTransfer.getWorkRequestId());
            displayChatMessage(fileTransfer.getAgentName(), "Agent transferred a file. Please visit the link below to download it.", "");
            displayChatMessage(fileTransfer.getAgentName(), transferUrl, "");
//return ((links.secureAllConnections ? 'https://' : 'http://') + links.webChatHost + "/services/customer/rest/attachment/" + fileUuid + "?workRequestId="+workRequestId);
        } catch (Exception e) {

        }
    }

    private void displayChatMessage(String displayName, String message, String time) {
        ChatMessage cm = new ChatMessage();
        cm.setName(displayName);
        cm.setMessage(message);
        cm.setTime(MessageParser.getTime(time));
        cm.setSenderType(1);
        activity.chatFragment.showAgentMessage(cm);
        showCoBrowseWindowMessages(cm);
    }


    //show the Agent is typing Message
    public void putAgentIsTyping(CustomerJsonWrapper wrapper) {
        Log.v("Info", activity.activityName + "  putAgentIsTyping()");
        AgentIsTyping isTyping = (AgentIsTyping) wrapper.getBody();
        activity.chatFragment.showAgentIsTyping(isTyping);
    }

    //show the agent message
    public void putAgentMessage(CustomerJsonWrapper wrapper) {
        Log.v("Info", activity.activityName + "  getPagePushMessageType()");
        NewMessageNotification am = null;
        try {
             am = (NewMessageNotification) wrapper.getBody();
        }
        catch (ClassCastException e){
            try {
                Log.e("CastError",e.getMessage());
                am = (NewAutomationMessageNotification) wrapper.getBody();
            }catch (ClassCastException ex){
                Log.e("CastError",e.getMessage());
            }
        }
        displayChatMessage(am.getDisplayName(), am.getMessage(), am.getTimestamp());
    }

    // show page-push message
    public void getPagePushMessageType(CustomerJsonWrapper wrapper) {
        Log.v("Info", activity.activityName + "  getPagePushMessageType()");
        PagePush pagePush = (PagePush) wrapper.getBody();
        String url = pagePush.getPagePushURL();
        Log.v("Info", "Page-Push Message: " + url);
        if (isCoBrowse(url)) {

            Log.v("Info", "Message was co-browse: "+url.toString());
            //get the Key and html file name from the URl
            Uri uri = Uri.parse(url);
            String host = Global.addressesMap.get("CoBrowse");
            String key = uri.getQueryParameter("key");

            Log.v("Info", "Key: " + key + " Host: " + host);
            loadCoBrowseURL(url, key, host);
        } else {
            Log.v("Info", "Message was NOT co-browse: "+url.toString());
            putAgentPagePush(pagePush);
        }
    }

    public void notifyNewCoBrowseSessionKeyMessage(CustomerJsonWrapper wrapper) {
        String key = ((NewCoBrowseNotification)wrapper.getBody()).getSessionKey();
        String host = Global.addressesMap.get("CoBrowse");
        loadDependenciesJS(key, host);
    }

    //close coBrowse if open and launch next intent when closeChatNotification received
    public void closeChat(CustomerJsonWrapper wrapper) {
        Log.v("Info", activity.activityName + " closeChat()");
        activity.coBrowseWrapper.setVisibility(View.GONE);

        if (!activity.isStopped) {
            executeFunctionJS("stopSession");
        }
        CloseConversationNotice closeConversationNotice = (CloseConversationNotice) wrapper.getBody();
        if (closeConversationNotice.isResult()) {
            fireMainActivityIntent();

        }
    }

    private void fireCloseIntent() {

        Log.v("Info",activity.activityName + " fireCloseIntent()");
        Intent intent = new Intent(activity, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("CLOSE", true);
        activity.startActivity(intent);
        activity.finish();
    }

    //remove the UI controls when the agent has left the chat
    private void putParticipantLeave(CustomerJsonWrapper wrapper) {
        Log.v("Info", activity.activityName + " putParticipantLeave()");
        ParticipantLeave leave = (ParticipantLeave) wrapper.getBody();
        String leaveReason = leave.getLeaveReason();
        String agentName = activity.agentMap.get(leave.getAgentId());
        String agentID = leave.getAgentId();
        List<CustomerParticipant> participants = leave.getParticipants();
        if (participants.size()>0) {
            CustomerParticipant participant = participants.get(0);
            if(participant.getId().equalsIgnoreCase(agentID)) {
                return;
            }
        }
        String closeMessage;
        if(leave.getEndChatFlag()) {
            activity.agentHasLeft = true;
            hideChatUI(activity.chatFragment);
            closeKeyboard();
            hideChatWindow(activity.browseFragment.agentChatWindow, activity.chatBubble);
            if (!leave.getAgentId().equals("AvayaAutomatedResource")) {
                if (agentName == null) {
                    closeMessage = "The Agent has left the chat. Chat will close after 5 sec";
                } else {
                    closeMessage = "" + agentName + " has left the chat. Chat will close after 5 sec";
                }
                Toast.makeText(activity, closeMessage, Toast.LENGTH_LONG).show();
                timer = new Timer();
                timer.schedule(new CloseChatTask(), 5000);
            }
            agentsMap.remove(agentName);
        } else {
            if(agentsMap.size() > 0 && agentsMap.containsKey(agentID)) {
                String role = agentsMap.get(agentID);
                closeMessage = "The  " + role + "  has left the chat.";
                Toast.makeText(activity, closeMessage, Toast.LENGTH_LONG).show();
                agentsMap.remove(agentID);
            } else if (participants.size() == 0) {
                if (leaveReason.equalsIgnoreCase("transfer")) {
                    Toast.makeText(activity, "Transferring to another service. Please remain in the chat", Toast.LENGTH_LONG).show();
                } else if (leaveReason.equalsIgnoreCase("transfer_to_user")) {
                    Toast.makeText(activity, "Transferring to User. Please remain in the chat", Toast.LENGTH_LONG).show();
                }
            }
        }

    }

    class CloseChatTask extends TimerTask {
        public void run() {
            fireCloseChat();
            timer.cancel();
        }
    }



    //show the UI controls when an agent joins the chat
    private void putParticipantJoin(CustomerJsonWrapper wrapper) {
        Log.v("Info", activity.activityName + " putParticipantJoin()");
        NewParticipant participant = (NewParticipant) wrapper.getBody();
        String role = participant.getRole().replace("_", " ");
        String displayName = participant.getDisplayName();
        String agentID = participant.getAgentId();
        agentsMap.put(agentID, role);
        if (!participant.getAgentId().equals("AvayaAutomatedResource")) {
            Toast.makeText(activity, " The " + displayName + " has joined the Chat as a " + role, Toast.LENGTH_SHORT).show();
        }
        activity.agentMap.put(participant.getAgentId(), participant.getDisplayName());
        activity.currentAgent = participant.getDisplayName();
        showChatUI(activity.chatFragment);
    }

    //get acknowledgement that customer message was received
    private void getCustomerAck(CustomerJsonWrapper wrapper) {
        Log.v("Info", activity.activityName + " getCustomerAck()");
        NewMessageAck ack = (NewMessageAck) wrapper.getBody();
        Log.i("Info", "Message sent successfully?: " + ack.getAccepted());
    }

    // a window that shows agent messages in the coBrowse view
    private void showCoBrowseWindowMessages(ChatMessage cm) {
        Log.v("Info", activity.activityName + " showCoBrowseWindowMessages()");
        if (!ChatActivity.chatIsVisible) {

            activity.chatBubble.setVisibility(View.INVISIBLE);
            activity.chatBubble.setVisibility(View.VISIBLE);
            Animation animation = android.view.animation.AnimationUtils.loadAnimation(activity, R.anim.stretch_n_spin);
            activity.chatBubble.setAnimation(animation);
            activity.chatBubble.setText("!");
            activity.chatUtils.getNotificationSound();

            if (!activity.isLocked) {
                setAgentChatWindow();
                activity.isLocked = true;
            }
            showMessageInCoBrowse(cm);
        } else {
            hideChatWindow(activity.browseFragment.agentChatWindow, activity.chatBubble);
        }
    }

    //place the coBrowse window in the coBrowse window
    public void setAgentChatWindow() {
        Log.v("Info", activity.activityName + " setAgentChatWindow()");
        RelativeLayout root = (RelativeLayout) activity.findViewById(R.id.co_browse_fragment_root);
        activity.browseFragment.agentChatWindow.setVisibility(View.GONE);
//get the width, height and pixel density of the current device screen.
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        float dp = activity.getResources().getDisplayMetrics().density;
        float h = metrics.heightPixels / dp;

        int height = Math.round(h);


        activity.browseFragment.agentChatWindow.setX(1);
        activity.browseFragment.agentChatWindow.setY(height / 2);
        root.addView(activity.browseFragment.agentChatWindow);
        Log.v("Info", "X:" + activity.browseFragment.agentChatWindow.getX() + " Y:" + activity.browseFragment.agentChatWindow.getY());

        activity.input = (EditText) activity.findViewById(R.id.co_browse_input_et);
        activity.sendBtn = (Button) activity.findViewById(R.id.co_browse_send_btn);
        activity.sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (activity.input.getText().length() > 0) {
                    String myInput = String.valueOf(activity.input.getText());
                    activity.setCoBrowseMessage(myInput);
                    activity.input.setText("");
                } else {
                    Toast toast = Toast.makeText(activity, "Add a message", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 0);
                    toast.show();
                }
            }
        });

        activity.closeBrowse = (ImageView) activity.findViewById(R.id.close_cobrowse_iv);
        activity.closeBrowse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.browseFragment.agentChatWindow.setVisibility(View.GONE);
                activity.chatBubble.setVisibility(View.VISIBLE);
                activity.chatBubble.setText("");
            }
        });

    }

    //set co-browse message
    private void showMessageInCoBrowse(ChatMessage cm) {
        Log.v("Info", activity.activityName + " showMessageInCoBrowse()");
        TextView messageTv = (TextView) activity.findViewById(R.id.agent_output_tv);
        messageTv.setText(cm.getMessage());
        TextView labelTv = (TextView) activity.findViewById(R.id.agent_label_tv);
        labelTv.setText(cm.getName());
        TextView timeTv = (TextView) activity.findViewById(R.id.agent_time_tv);
        timeTv.setText(cm.getTheTime());
    }

    //load co-browse url into web-view
    public void loadCoBrowseURL(String pagePush, final String key, final String host) {
        Log.v("Info", activity.activityName + " loadCoBrowseURL()");
        Log.v("Info","PagePush: "+pagePush+"\nKey: "+key+"\nHost: "+host);
        activity.browseFragment.webView.loadUrl(pagePush);
        //wait for page to load
        activity.browseFragment.webView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                loadDependenciesJS(key, host);
            }
        });
        activity.browseFragment.setUrl(pagePush);
    }

    //check the url string for a co-browse key
    public static boolean isCoBrowse(String url) {
        return url.contains("?key=");
    }
//TODO there seems to be an issue with the webView
    /*
    V/Console: Line No: |1 Message: |Uncaught TypeError: coBrowse.loadDependencies is not a function Source:
    I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: coBrowse.loadDependencies is not a function", source:  (1)

     */
    //setup coBrowse interaction
    public void loadDependenciesJS(String key, String host) {
        Log.v("Info", activity.activityName + " loadDependenciesJS()");
        String userName = Global.notification.getIntrinsics().getName();
        if (userName == null){

            userName = "undefined";
        }
        String jsLoadDependencies = "javascript:coBrowse.loadDependencies(" + "'" + host + "'," + "'" + userName + "'," + "'" + key + "'" + ");";
        activity.browseFragment.webView.loadUrl(jsLoadDependencies);
        activity.browseFragment.setUrl(jsLoadDependencies);
    }

    //call to javascript functions in co-browse URL
    public void executeFunctionJS(String jsMethod) {
        Log.v("Info", activity.activityName + " executeFunctionJS()");
        String jsString = "javaScript:coBrowse." + jsMethod + "();";
        activity.browseFragment.webView.loadUrl(jsString);
    }

    //show a visual cue that a message has been received from the agent in CoBrowse window
    public void setAgentMessageAlert() {
        Log.v("Info", activity.activityName + " setAgentMessageAlert()");
        activity.chatBubble.setVisibility(View.INVISIBLE);
        activity.chatBubble.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //remove the chat bubble if the dialog box is visible
                if (activity.browseFragment.agentChatWindow.getVisibility() == View.VISIBLE && activity.chatBubble.getVisibility() == View.INVISIBLE) {
                    activity.browseFragment.agentChatWindow.setVisibility(View.GONE);

                } //remove the chat bubble if both are visible
                else if (activity.browseFragment.agentChatWindow.getVisibility() == View.VISIBLE && activity.chatBubble.getVisibility() == View.VISIBLE) {
                    activity.chatBubble.setVisibility(View.INVISIBLE);

                } else {
                    activity.chatBubble.setVisibility(View.INVISIBLE);
                    activity.browseFragment.agentChatWindow.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    //switch views between chat and co-browse fragments
    public void switchFragment() {
        Log.v("Info", activity.activityName + " switchFragment()");
        Button b = (Button) activity.findViewById(R.id.co_browse_switch);
        closeKeyboard();

        if (activity.browseFragment.isHidden()) {
            Log.v("Switch", "Entered if isHidden");
            activity.getFragmentManager().beginTransaction().setCustomAnimations(R.animator.card_flip_right_in,
                    R.animator.card_flip_right_out,
                    R.animator.card_flip_left_in,
                    R.animator.card_flip_left_out).hide(activity.chatFragment).show(activity.browseFragment).commit();
            b.setText(activity.getString(R.string.chat_label));
            ChatActivity.chatInBackground();

            Log.v("Info", "Co_Browse fragment is visible: " + !ChatActivity.chatIsVisible);
        } else {

            activity.getFragmentManager().beginTransaction().setCustomAnimations(R.animator.card_flip_left_in,
                    R.animator.card_flip_left_out,
                    R.animator.card_flip_right_in,
                    R.animator.card_flip_right_out).hide(activity.browseFragment).show(activity.chatFragment).commit();
            b.setText(activity.getString(R.string.co_browse_label));
            ChatActivity.chatInForeGround();
            activity.chatBubble.setVisibility(View.GONE);
            Log.v("Info", "Chat Fragment is visible: " + ChatActivity.chatIsVisible);
        }

    }

    //check if the customer wants to leave the chat with a dialog
    public void closeChatDialog() {
        Log.v("Info", activity.activityName + "closeChatDialog()");
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(R.string.leave_chat_dialog);
        String yes = activity.getString(R.string.ok);
        String no = activity.getString(R.string.cancel);

        builder.setPositiveButton(yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                fireCloseChat();
            }
        }).setNegativeButton(no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void fireCloseChat() {
        Intent serviceIntent = new Intent(activity, WebSocketService.class);
        activity.getApplicationContext().stopService(serviceIntent);
        if (!activity.agentHasLeft) {
            sendCloseChatRequest();
        }
        fireMainActivityIntent();

        // launchSurveyActivity();
    }


    //toggle visibility of co-browse buttons
    public void showAndHideCoBrowseBtns() {
        Log.v("Info", activity.activityName + " showAndHideCoBrowseBtns()");
        if (!activity.isUp) {
            showCoBrowseButtons();
        } else {
            hideCoBrowseButtons();
        }
    }

    //show the co-browse interaction button
    private void showCoBrowseButtons() {
        Log.v("Info", activity.activityName + " showCoBrowseButtons()");
        activity.coBrowseControlsButton.setImageResource(R.drawable.ic_action_hide);
        activity.coBrowseBtnLayout.setVisibility(View.VISIBLE);
        activity.coBrowseBtnLayout.startAnimation(activity.slideUpBody);
        activity.coBrowseControlsButton.startAnimation(activity.slideUpTag);
        activity.isUp = true;
    }

    //hide the co-browse interaction button
    public void hideCoBrowseButtons() {
        Log.v("Info", activity.activityName + " hideCoBrowseButtons()");
        activity.coBrowseControlsButton.setImageResource(R.drawable.ic_action_show);
        activity.coBrowseBtnLayout.setVisibility(View.GONE);
        activity.coBrowseBtnLayout.startAnimation(activity.slideDownBody);
        activity.coBrowseControlsButton.startAnimation(activity.slideDownTag);
        activity.isUp = false;
    }


    //used to display incoming message that is lost when app is in background
    public void setMessageAfterBackground() {
        Log.v("Info", activity.activityName + " setMessageAfterBackground()");
        List<ChatMessage> preservedMessageList = activity.wsService.getPersistedChatMessageList();
        if (!preservedMessageList.isEmpty()) {
            Log.v("Info", "InList size = " + preservedMessageList.size());
            activity.chatFragment.setMessageList(preservedMessageList);

        }
    }

    //get the participant join message from the previous activity
    public NewParticipant getParticipantJoinFromIntent() {
        Log.v("Info", activity.activityName + " getParticipantJoinFromIntent()");
        String participants = activity.waitIntent.getStringExtra("newParticipant");
        Log.v("Info", "Participant Join: " + participants);
        if (participants != null) {
            CustomerJsonWrapper wrapper = MessageParser.jsonStringToJava(participants);
            assert wrapper != null;
            return (NewParticipant) wrapper.getBody();
        }
        return null;
    }

    //hide chat UI when the agent has sent a close chat message
    public void disableChatFromCLoseNotification() {
        if (activity.wsClient != null) {
            Log.v("Info", "wsClient is not Null");
            Log.v("Info", "" + activity.wsClient.getConnection().getReadyState());
            if (activity.wsClient.getConnection().getReadyState().toString().trim().equals("CLOSED")) {
                Log.v("Info", "hideChatWindow");
                hideChatUI(activity.chatFragment);
                activity.agentHasLeft = true;
            }
        }
    }

    private void fireMainActivityIntent() {

        Log.v("Info",activity.activityName + " fireMainActivityIntent()");
        Intent intent = new Intent(activity.getApplicationContext(), MainActivity.class);
        activity.startActivity(intent);
        activity.finish();
        fireCloseIntent();
    }
}
