/*
 * /////////////////////////////////////////////////////////////////////////////////
 * //
 * // 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.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.R;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.UtilClasses.MainActivityDialogUtils;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.UtilClasses.MainActivityUtils;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.adapters.ProductListAdapter;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.classes.MessageParser;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.ewt_model.ServiceMapContainer;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.ewt_model.ServiceMapPriority;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.RestConnection;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class MainActivity extends AppCompatActivity {

    public final String activityName = this.getClass().getSimpleName();
    public ProductListAdapter adapter;
    public ListView homeList;
    public Intent launcherIntent;
    public FloatingActionButton fab;
    public ServiceMapPriority serviceMapWithPriority;

    public MainActivityUtils mainUtils;
    public MainActivityDialogUtils dialogUtils;
    public List<String> attributesList;
    public Map<String, String> addressMap;
    public Map<String, List<String>> attributesMap;
    public Set<String> categorySet, attributeSet;

    ObjectMapper mapper;
    public int ewtIndex;
    public int ewtTime;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Log.v("Info", activityName + " onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.canShowOverflowMenu();

        serviceMapWithPriority = new ServiceMapPriority();
        attributesMap = new HashMap<>();

        addressMap = new HashMap<>();
        mapper = new ObjectMapper();

        //adding shared preferences to attributes list

        categorySet = new HashSet<>();
        attributeSet = new HashSet<>();
        fab = (FloatingActionButton) findViewById(R.id.fab);
        ewtIndex = 1;
        ewtTime = 0;
        launcherIntent = new Intent(this, RequestChatFormActivity.class);
        mainUtils = new MainActivityUtils(this);
        dialogUtils = new MainActivityDialogUtils(this);

        createAttributesList();

        mainUtils.setHomeScreenItems();
        mainUtils.populateMenuItems();
        mainUtils.setFabVisible(false);
        //used to close the entire app on the survey-activity
        if (attributesList.size()>0) {
            requestEWT(1);
        }

        finalClose();
    }

    private void finalClose() {
        Intent closeIntent = getIntent();
        Log.v("Info", activityName + " " + closeIntent.describeContents());
//        if (closeIntent != null && closeIntent.getBooleanExtra("CLOSE", false)) {
//            Log.v("Info", activityName + " entering close launcherIntent");
//            finish();
//
//        }
    }


    private void createAttributesList() {
        if (dialogUtils.retrieveAttributes() != null) {

            attributesList = dialogUtils.retrieveAttributes();
            Log.v("Info", "attribute List size: " + attributesList.size());
        } else {
            attributesList = new ArrayList<>();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

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

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onRestoreInstanceState(savedInstanceState, persistentState);
    }

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

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

    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.v("Info", activityName + " onCreateOptionsMenu()");
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.v("Info", activityName + " onOptionsItemSelected()");
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            case R.id.action_attributes:
                dialogUtils.showAttributesDialog();
                return true;
            case R.id.action_addresses:
                dialogUtils.showAddressDialog();
                return true;
            case R.id.action_about:
                dialogUtils.showAboutDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    //build json string to request ewt
    public void requestEWT(int priority) {
        //create temporary collection to avoid concurrent modification exception
        Set<String> set = new HashSet<>();
        set.addAll(attributesList);
        //set.add("Channel.Chat");
        for (String attribute : set) {
            mainUtils.addAttributes(attribute);
        }

        Log.v("Info", activityName + " requestEWT()");
        serviceMapWithPriority.setPriority(priority);
        ServiceMapContainer container = new ServiceMapContainer();
        container.getServiceMap().put(String.valueOf(ewtIndex++), serviceMapWithPriority);
        String ewtRequest = MessageParser.javaObjectToJson(container);
        Log.v("Info", "Request: " + ewtRequest);
        new AsyncPostEWTRequest().execute(ewtRequest);
        mainUtils.setFabVisible(true);

    }

    //Rest call on separate thread to get EWT
    private class AsyncPostEWTRequest extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            String response = null;

            if (!addressMap.containsKey("WorkAssignment")) {
                Log.e("Info", "Work Assignment Address was null");
            } else {
                String uri = addressMap.get("WorkAssignment") + "/services/CustomerControllerService/gila/ewt/request";
                response = RestConnection.POSTRequest(params[0], uri);
                Log.e("Info", "Work Assignment Address was " + uri);
                Log.e("Info", "Work Assignment responce is " + response);
            }
            return response;
        }

        @Override
        protected void onPostExecute(String response) {
            extractEWTFromResponse(response);
            mainUtils.setFabVisible(true);


        }

        private void extractEWTFromResponse(String response) {
            if (response == null) {

                Log.v("Info", "WA Response was Null");
            } else {
                Log.v("Info", "POST RESPONSE: " + response);
                JsonNode root;
                JsonNode head;

                try {
                    root = mapper.readTree(response);
                    head = root.path("serviceMetricsResponseMap");

                    int bodyCount = 1;
                    //1.process the return
                    if (!head.isMissingNode()) getEWT(response, head, bodyCount);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        //get the EWT to offer or deny chat
        private void getEWT(String response, JsonNode head, int bodyCount) {
            JsonNode body;
            JsonNode priorityNode;
            JsonNode metricsNode;
            JsonNode ewtNode;
            body = head.path(Integer.toString(bodyCount));
            //determine category and contents of attributes
            priorityNode = body.path("priority");
            Log.v("Info", "EWT Priority: " + priorityNode.asText());

            metricsNode = body.path("metrics");
            if (!metricsNode.isMissingNode()) {
                ewtNode = metricsNode.path("EWT");
                Log.v("Info", "EWT 1: " + ewtNode.asText());
                ewtTime = (int) Math.round(ewtNode.asDouble());

            } else {

                Log.e("Error", " Offering Chat, WA Metrics response does not contain an EWT:" + response);
            }
        }
    }
}
