/*
 * /////////////////////////////////////////////////////////////////////////////////
 * //
 * // 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.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.R;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.UtilClasses.BuildRequestUtils;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.UtilClasses.RequestChatUtils;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.model.CustomerJsonWrapper;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.WebSocketService;

import org.java_websocket.client.WebSocketClient;


import java.util.ArrayList;
import java.util.List;


public class RequestChatFormActivity extends AppCompatActivity {

    public final String activityName = this.getClass().getSimpleName();
    public TextView nameTV;
    public TextView emailTv;
    public TextView phoneTv;
    public CheckBox requestTranscriptCB;
    public boolean isRequestChatVisible;
    public boolean isBound = false;
    public String channelType;
    public String ccAddress;
    public String packageName;
    public WebSocketService wsService;
    public WebSocketClient wsClient;
   public Intent intentFromMain;

    BuildRequestUtils buildRequestUtils;
    RequestChatUtils requestChatUtils;
    public List<String> attributesList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Log.v("Info",activityName+" onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request_chat_form);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        packageName = getApplicationContext().getPackageName();
        nameTV = (TextView) findViewById(R.id.name_tv);
        emailTv = (TextView) findViewById(R.id.email_tv);
        phoneTv = (TextView) findViewById(R.id.phone_tv);
        attributesList = new ArrayList<>();
        intentFromMain = getIntent();
        requestTranscriptCB = (CheckBox) findViewById(R.id.req_transcript_cb);
        //explicitly starting the service
        Intent serviceIntent = new Intent(this, WebSocketService.class);
        startService(serviceIntent);
        requestChatUtils = new RequestChatUtils(this);
        requestChatUtils.getAttributesFromIntent();
        ccAddress = intentFromMain.getStringExtra("Address");
        buildRequestUtils = new BuildRequestUtils();
        bindToWebSocket();

    }

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

    }

    @Override
    public void onStop() {
        Log.v("Info",activityName+" onStop()");
        super.onStop();
        unbindFromWebSocket();
    }

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

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

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

    // method called by submit button
    public void submitChatRequest(View v) {
        Log.v("Info",activityName+" submitChatRequest()");
        //get values from text-fields
        String email = emailTv.getText().toString();
        String name = nameTV.getText().toString();
        String phoneNo = phoneTv.getText().toString();
        //if the email structure is not blank or is invalid, the clear the text field an inform the user
        if (BuildRequestUtils.isValidEmail(email) || email.length() == 0) {
            CustomerJsonWrapper wrapper = requestChatUtils.buildRequestChat(name, phoneNo, email);
            requestChatUtils.requestChat(wrapper);
        } else {
            emailTv.setText("");
            Toast.makeText(this, "email address was not valid, please re-enter", Toast.LENGTH_SHORT).show();
        }
    }

/*Methods for handling the connection and communication with the background Service hosting the web-socket*/

//receives broadcast messages from the web-socket service
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v("Info",activityName+" onReceive()");
            String inMessage = intent.getStringExtra("message");
            Log.v("Info", " Message from WS: " + inMessage);
            CustomerJsonWrapper wrapper = BuildRequestUtils.getMessageAsJava(inMessage);
            if (wrapper != null) {
                requestChatUtils.launchChatActivity(wrapper);
            } else {
                Log.v("Info", "Wrapper does not contain JSON Message");
            }
        }

    };
//connect to the service and initialise variables
    private 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();
            isBound = true;
            Log.v("Info", "Service in activity 1 " + wsService.toString());

          ccAddress = ccAddress +getString(R.string.cc_address_tail);

            Log.v("Info", "CC URI: " + ccAddress);
            wsService.setUri(ccAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            unbindFromWebSocket();
        }
    };

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

    private void unbindFromWebSocket() {
        Log.v("Info",activityName+" unbindFromWebSocket()");
        if (isBound) {
            Log.v("Info", "Unbinding Service");
            unbindService(serviceConnection);
            isBound = false;
        }
    }
}
