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


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.R;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.UtilClasses.ChatActivityUtils;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.ChatMessage;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.fragments.ChatActivityFragment;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.fragments.CoBrowseFragment;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewParticipant;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.Global;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.WebSocketService;

import org.java_websocket.client.WebSocketClient;

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


public class ChatActivity extends AppCompatActivity implements ChatActivityFragment.PagePushHandler, CoBrowseFragment.CoBrowseHandler {

    public final String activityName = this.getClass().getSimpleName();
    public static boolean appIsVisible;
    public static boolean chatIsVisible;
    public TextView chatBubble;

    Context context;
    public Intent waitIntent;
    public RelativeLayout coBrowseBtnLayout;
    public LinearLayout coBrowseWrapper;
    public FrameLayout rootLayout;
    public EditText input;
    Toolbar toolbar;
    public Button sendBtn;
    public Button stopCoBrowseBtn, pauseCoBrowseBtn;
    public Button revokeCoBrowseBtn;
    public Button coBrowseViewButton;
    public ImageButton coBrowseControlsButton;
    public ImageView closeBrowse;
    public ProgressBar pb;
    public ChatActivityFragment chatFragment;
    public CoBrowseFragment browseFragment;
    public WebSocketService wsService;
    public WebSocketClient wsClient;
    public ChatActivityUtils chatUtils;


    public boolean isBound, agentHasLeft, isLocked;
    //co-browse booleans
    public boolean isUp, isStopped, isPaused;
    public String inMessage;
    private String packageName;
    public Animation slideUpBody;
    public Animation slideDownBody;
    public Animation slideDownTag;
    public Animation slideUpTag;
    public Map<String, String> agentMap;
    public String currentAgent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        chatIsVisible = true;
        setContentView(R.layout.activity_chat);
        context = this;
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_close);
        chatFragment = new ChatActivityFragment();
        agentMap = new HashMap<>();
        browseFragment = new CoBrowseFragment();
        chatUtils = new ChatActivityUtils(this);
        if(Global.waitMessageActivity != null) {
            Global.waitMessageActivity.finish();
        }

        packageName = getApplicationContext().getPackageName();
        chatBubble = (TextView) findViewById(R.id.chat_bubble_tv);
        agentHasLeft = false;
        rootLayout = (FrameLayout) findViewById(R.id.rootView);
        coBrowseBtnLayout = (RelativeLayout) findViewById(R.id.co_browse_controls_lo);
        coBrowseControlsButton = (ImageButton) findViewById(R.id.show_co_browse_btn);
        coBrowseWrapper = (LinearLayout) findViewById(R.id.co_browse_wrapper);
        coBrowseViewButton = (Button) findViewById(R.id.co_browse_switch);
        stopCoBrowseBtn = (Button) findViewById(R.id.stop_co_browse_btn);
        pauseCoBrowseBtn = (Button) findViewById(R.id.pause_co_browse_btn);
        revokeCoBrowseBtn = (Button) findViewById(R.id.revoke_co_browse_btn);


        if (coBrowseViewButton != null) {
            coBrowseViewButton.setVisibility(View.INVISIBLE);
        }
        pb = (ProgressBar) findViewById(R.id.is_typing_pb);

        slideUpBody = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up_drawer);
        slideDownBody = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down_drawer);
        slideDownTag = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down_tag);
        slideUpTag = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up_tag);
        isLocked = false;
        waitIntent = getIntent();
        int containerID = R.id.rootView;
        NewParticipant participant = chatUtils.getParticipantJoinFromIntent();
        if (participant != null) {
            agentMap.put(participant.getAgentId(), participant.getDisplayName());
            currentAgent = participant.getDisplayName();
        }

            chatUtils.setInitialFragment(savedInstanceState, containerID);

        bindToWebSocketService();
        appInForeGround(true);
        chatUtils.setAgentMessageAlert();

        coBrowseViewButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatUtils.switchFragment();
            }
        });

        stopCoBrowseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (stopCoBrowseBtn.getText().equals(getString(R.string.stop))) {
                    chatUtils.executeFunctionJS("stopSession");
                }
            }
        });

//the pause/resume button for co-browse
        pauseCoBrowseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                coBrowsePauseResumeClick();

            }
        });
//the close button for co-browse
        coBrowseControlsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                chatUtils.showAndHideCoBrowseBtns();
            }
        });
//the revoke button for co-browse
        revokeCoBrowseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatUtils.executeFunctionJS("revokeControl");
            }
        });
    }

    private void coBrowsePauseResumeClick() {
        Log.v("Info", activityName + "  coBrowsePauseResumeClick()");
        if (pauseCoBrowseBtn.getText().toString().equals(getString(R.string.pause))) {
            pauseCoBrowseBtn.setText(R.string.resume);
        } else {
            pauseCoBrowseBtn.setText(R.string.pause);
        }
        chatUtils.executeFunctionJS("togglePause");
    }

    public static void appPaused() {
        appIsVisible = false;
    }

    public static void appResumed() {
        appIsVisible = true;
    }

    public static void chatInForeGround() {
        chatIsVisible = true;
    }

    public static void chatInBackground() {
        chatIsVisible = false;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        //detects notification click
        Log.v("Info", activityName + " onNewIntent()");
        wsService.setAppVisible(true, activityName);
    }

    @Override
    protected void onStart() {
        Log.v("Info", activityName + " onStart()");
        super.onStart();
        appInForeGround(true);
    }

    @Override
    protected void onStop() {
        Log.v("Info", activityName + " onStop()");
        super.onStop();
        unbindService(serviceConnection);
        appInForeGround(false);
        isBound = false;
    }

    @Override
    protected void onDestroy() {
        Log.v("Info", activityName + " onDestroy()");
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        Log.v("Info", activityName + " onPause()");
        super.onPause();
        appInForeGround(false);
        appPaused();
        unregisterReceiver(receiver);
    }

    @Override
    public void onBackPressed() {
        Log.v("Info", activityName + "  onBackPressed()");
        chatUtils.closeChatDialog();

    }

    @Override
    protected void onResume() {
        Log.v("Info", activityName + "  onResume()");
        super.onResume();
        bindToWebSocketService();
        appInForeGround(true);
        appResumed();
        registerReceiver(receiver, new IntentFilter(packageName));
    }


    public BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //listen for agent messages here
            inMessage = intent.getStringExtra("message");
            chatUtils.getWsMessageByType(inMessage);
        }
    };

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        Log.v("Info", activityName + "  onSaveInstanceState()");
        super.onSaveInstanceState(outState, outPersistentState);

        getFragmentManager().beginTransaction().detach(chatFragment).detach(browseFragment).commit();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.v("Info", activityName + "  onOptionsItemSelected()");
        /**close the web-socket here**/
        switch (item.getItemId()) {
            case android.R.id.home:
                chatUtils.closeChatDialog();
                break;
        }
        return true;
    }


    private void bindToWebSocketService() {
        Log.v("Info", activityName + "  bindToWebSocketService()");
        Intent wsIntent = new Intent(this, WebSocketService.class);
        if (!isBound) {
            bindService(wsIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            isBound = true;
        }
    }

    public ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.v("Info", activityName + " onServiceConnected()");
            WebSocketService.LocalBinder binder = (WebSocketService.LocalBinder) service;
            wsService = binder.getService();
            wsService.setAppVisible(true, activityName);
            isBound = true;
            wsClient = wsService.getWsClient();
            chatUtils.setMessageAfterBackground();
            chatUtils.disableChatFromCLoseNotification();
            appInForeGround(true);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.v("Info", activityName + " onServiceDisconnected()");
            isBound = false;

        }
    };


    @Override
    public void appInForeGround(boolean b) {
        Log.v("Info", activityName + " appInForeGround()");
        if (wsService != null) {

            wsService.setAppVisible(b, activityName);
        }
    }

    @Override
    public void saveMessageHistory(List<ChatMessage> cm) {
        Log.v("Info", activityName + " saveMessageHistory()");
        wsService.setPersistedChatMessageList(cm);
    }


    @Override
    public void setCoBrowseMessage(String message) {
        Log.v("Info", activityName + " setCoBrowseMessage()");
        chatFragment.showCustomerCoBrowseMessage(message);
    }

}
