/*
 * /////////////////////////////////////////////////////////////////////////////////
 * //
 * // 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.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.activities.RequestChatFormActivity;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.activities.WaitMessageActivity;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.classes.MessageParser;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.CustomerJsonWrapper;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.Intrinsics;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.RequestChatNotification;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.NewChatRequest;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.WsErrorMessage;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.Global;

import org.java_websocket.exceptions.WebsocketNotConnectedException;

public class RequestChatUtils {

    private RequestChatFormActivity activity;

    public RequestChatUtils(RequestChatFormActivity activity) {
        this.activity = activity;
    }

    //send request chat over web-socket
    public void requestChat(CustomerJsonWrapper wrapper) {
        //sending request chat over websocket
        String reqChatString = MessageParser.javaObjectToJson(wrapper);
        Log.i("Info", reqChatString);

        if (openWsConnection()) {
            activity.wsClient.send(reqChatString);

        } else {
            Toast.makeText(activity, "Could not connect to Server @ " + activity.ccAddress, Toast.LENGTH_LONG).show();
        }
    }


    //the webSocket interface
    public boolean openWsConnection() {

        if (activity.ccAddress != null) {
            try {
                activity.wsService.onConnectWs();
            } catch (WebsocketNotConnectedException e) {
                Log.e("Error", "cannot connect to Web Socket");
            }
            activity.wsClient = activity.wsService.getWsClient();
            activity.wsClient.connect();
            boolean isConnected = false;
            int x = 0;
            //attempt web socket connection
            while (x < 10) {
                if (activity.wsClient.getReadyState().toString().equals("OPEN")) {
                    Log.v("Info", "Connected");
                    isConnected = true;
                    Log.v("WS", activity.wsClient.getReadyState().toString());
                    break;
                }
                Log.v("WS", activity.wsClient.getReadyState().toString() + " attempt: " + x);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                x++;
                if (x >= 10) {
                    activity.wsClient.close();
                    isConnected = false;
                }
            }

            return isConnected;
        } else {
            return false;
        }
    }

// extract the attributes sent from the main activity
    public void getAttributesFromIntent() {
        //getting the channel type from the previous activity
        activity.attributesList = activity.intentFromMain.getStringArrayListExtra("Attributes");
        if (activity.attributesList.size() < 1) {
            Log.v("Info", "No Attributes Available");
        }
        activity.channelType = activity.intentFromMain.getStringExtra("Channel");
        //show request transcript for Text Chat channel only
        activity.isRequestChatVisible = activity.channelType.equals("Chat");
        if (!activity.isRequestChatVisible) {
            activity.requestTranscriptCB.setVisibility(View.INVISIBLE);
        }
    }



//construct the request chat object
    public CustomerJsonWrapper buildRequestChat(String name, String phoneNo, String email) {
        CustomerJsonWrapper wrapper = new CustomerJsonWrapper();
        wrapper.setType("request");
        Intrinsics intrinsics = BuildRequestUtils.setIntrinsics(name, phoneNo, email, activity, activity.channelType, activity.attributesList);
        NewChatRequest chatRequest = new NewChatRequest();
        chatRequest.setPriority(5);
        chatRequest.setIntrinsics(intrinsics);
        boolean checked = false;
        chatRequest.setDeviceType("Android");
        if (activity.isRequestChatVisible) {
            checked = activity.requestTranscriptCB.isChecked();
        }
        chatRequest.setRequestTranscript(checked);
        if (Global.addressesMap.get("RoutePoint") != null) {
            chatRequest.setRoutePointIdentifier(Global.addressesMap.get("RoutePoint"));
        } else {
            chatRequest.setRoutePointIdentifier("");
        }
        if (Global.addressesMap.get("WorkFlow") != null) {
            chatRequest.setWorkFlowType(Global.addressesMap.get("WorkFlow"));
        } else {
            chatRequest.setWorkFlowType("");
        }
        chatRequest.setWorkRequestId("");
        wrapper.setBody(chatRequest);
        return wrapper;
    }

// launch the Chat activity on Request chat notification
    public void launchChatActivity(CustomerJsonWrapper wrapper) {

        String className = wrapper.getBody().getClass().getSimpleName();

        if (wrapper.getType().equals("notification") && className.equals("RequestChatNotification")) {
            Global.notification = (RequestChatNotification) wrapper.getBody();
            Intent startIntent = new Intent(activity, WaitMessageActivity.class);
            activity.startActivity(startIntent);
            activity.finish();

        } else if (className.equals("WsErrorMessage")) {

            WsErrorMessage wsErrorMessage = (WsErrorMessage) wrapper.getBody();
            Log.e("Error", "Code: " + wsErrorMessage.getCode() + "\nMessage: " + wsErrorMessage.getErrorMessage());

        } else {
            Log.e("Error", "Received:\n" + wrapper.toString() + "\nExpected: RequestChatNotification");
        }

    }
}
