/*
 * /////////////////////////////////////////////////////////////////////////////////
 * //
 * // 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.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.R;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.activities.MainActivity;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.services.Global;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivityDialogUtils {

    private MainActivity activity;
    private SharedPreferences myPreferences;
    private SharedPreferences.Editor myEditor;
    private final String[] mapKeys = {"CustomerController", "WorkAssignment", "WorkFlow", "RoutePoint"};


    public MainActivityDialogUtils(MainActivity activity) {
        this.activity = activity;
        myPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
        myEditor = myPreferences.edit();
        initAdressMap(mapKeys);
    }

    public void showAboutDialog() {

        final Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.dialog_about_text);
        dialog.setTitle("About");

        dialog.show();

    }


    //menu to set various addresses
    public void showAddressDialog() {

        final Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.dialog_address_form);
        dialog.setTitle("Add Addresses");

        // extract dialog inputs
        int[] buttonIdList = {R.id.customer_controller_btn, R.id.work_assignment_btn, R.id.work_flow_btn, R.id.route_point_btn};
        final int[] editTextIdList = {R.id.customer_controller_et, R.id.work_assignment_et, R.id.work_flow_et, R.id.route_point_et};


        populateAddressesDialog(dialog, mapKeys, editTextIdList);
        for (int i = 0; i < buttonIdList.length; i++) {
            initialiseAddressDialogControls(dialog, buttonIdList[i], editTextIdList[i], mapKeys[i]);
        }
        dialog.show();

        Button close = (Button) dialog.findViewById(R.id.ip_setup_closebtn);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
            }
        });

        Button clear = (Button) dialog.findViewById(R.id.clear_ip_btn);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int anEditTextIdList : editTextIdList) {
                    EditText et = (EditText) dialog.findViewById(anEditTextIdList);
                    Log.v("Info", "CLEARED");
                    et.setText("");
                    et.setTextColor(Color.parseColor("#000000"));
                    et.setEnabled(true);
                    activity.addressMap.clear();
                }
                for (String name : mapKeys) {
                    myEditor.putString(name, "");
                }
                myEditor.commit();
            }
        });
    }

    //sets up the inputs for the various address fields
    private void initialiseAddressDialogControls(final Dialog dialog, int buttonId, final int editTextId, final String name) {
        //get the customer controller ip

        final Button ccButton = (Button) dialog.findViewById(buttonId);
        ccButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EditText et = (EditText) dialog.findViewById(editTextId);
                if (et.getText().length() > 0) {

                    String tempAddress = et.getText().toString();
                    et.setTextColor(activity.getResources().getColor(R.color.colorAccentLight));
                    myEditor.putString(name, tempAddress);
                    myEditor.commit();
                    activity.addressMap.put(name, tempAddress);
                    Log.v("Info","Key: "+name+" value: "+ tempAddress);

                } else {
                    Toast.makeText(dialog.getContext(), R.string.value_prompt, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initAdressMap (String[] mapKeys) {
        for (int i = 0; i < mapKeys.length; i++) {
            String address = myPreferences.getString(mapKeys[i], "");
            if (address != null && !address.equalsIgnoreCase("")) {
                activity.addressMap.put(mapKeys[i], address);
            }
        }
    }

    //populates each address field with previously entered and saved values
    private void populateAddressesDialog(Dialog dialog, String[] mapKeys, int[] editTextList) {
        for (int i = 0; i < mapKeys.length; i++) {
            String address = myPreferences.getString(mapKeys[i], "");
            if (address != null && !address.equalsIgnoreCase("")) {
                EditText et = (EditText) dialog.findViewById(editTextList[i]);
                et.setText(address);
                et.setTextColor(activity.getResources().getColor(R.color.colorAccentLight));
            }
        }

    }

    public void showAttributesDialog() {
        final Dialog attrDialog = new Dialog(activity);
        attrDialog.setContentView(R.layout.dialog_attributes_form);
        attrDialog.setTitle("Add Attributes");
        final Button attrButton = (Button) attrDialog.findViewById(R.id.add_attribute_btn);
        final EditText et = (EditText) attrDialog.findViewById(R.id.set_attribute_et);
        final ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_list_item_1, activity.attributesList);
        ListView lv = (ListView) attrDialog.findViewById(R.id.show_atttributes_lv);
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        attrButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = et.getText().toString();
                if (isAttributePattern(input)) {
                    et.setText("");
                    adapter.notifyDataSetChanged();
                    activity.mainUtils.addAttributes(input);

                    Toast.makeText(activity, "Attribute Added", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, "Attribute was not  properly formatted", Toast.LENGTH_SHORT).show();
                }
            }
        });

        attrDialog.show();

        Button close = (Button) attrDialog.findViewById(R.id.close_attr_dialog_btn);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v("Info","");
                preserveAttributes(activity.attributesList);
                if (activity.attributesList.size() > 0 ){
                    activity.requestEWT(1);
                }
                attrDialog.dismiss();
            }
        });

        Button clear = (Button) attrDialog.findViewById(R.id.clear_attr_dialog_btn);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (activity.attributesList.size() > 0) {
                    activity.attributesList.remove(activity.attributesList.size() - 1);
                    preserveAttributes(activity.attributesList);
                    adapter.notifyDataSetChanged();

                }
            }
        });
    }

    //ensures that the attributes entered are dot separated strings
    private boolean isAttributePattern(String input) {

        Pattern p = Pattern.compile("^\\w+(\\.\\w+)$");
        Matcher m = p.matcher(input);

        return m.matches();
    }

    //dialog box to verify that the customer wants to request a chat
    public void requestChatDialog() {
        //setting up the alert dialog

        Global.addressesMap = activity.addressMap;
        if (activity.addressMap.get("CustomerController") == null) {
            Toast.makeText(activity, "Set The Customer Controller Address Before Continuing", Toast.LENGTH_LONG).show();
        } else {
            activity.launcherIntent.putExtra("Channel", "Chat");
            activity.launcherIntent.putStringArrayListExtra("Attributes", (ArrayList<String>) activity.attributesList);
            preserveAttributes(activity.attributesList);
            activity.launcherIntent.putExtra("Address", activity.addressMap.get("CustomerController"));
            activity.startActivity(activity.launcherIntent);
        }
//        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
//
//        builder.setTitle(R.string.channel_type_dialog_title);
//        // builder.setMessage(R.string.dialog_label);
//        String yes = activity.getString(R.string.ok);
//        String no = activity.getString(R.string.cancel);
//
//        //setting radio buttons for chat type
//        final CharSequence[] chatTypes = {"Text Chat"};
//        builder.setSingleChoiceItems(chatTypes, 0, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                //set the channelType attribute here
//
//            }
//        }).setPositiveButton(yes, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//
//                Global.addressesMap = activity.addressMap;
//                if (activity.addressMap.get("CustomerController") == null) {
//                    Toast.makeText(activity, "Set The Customer Controller Address Before Continuing", Toast.LENGTH_LONG).show();
//                } else {
//                    ListView lw = ((AlertDialog) dialog).getListView();
//                    int checkedItem = lw.getCheckedItemPosition();
//                    setPositionIntent(checkedItem);
//                    activity.launcherIntent.putStringArrayListExtra("Attributes", (ArrayList<String>) activity.attributesList);
//                    preserveAttributes(activity.attributesList);
//                    activity.launcherIntent.putExtra("Address", activity.addressMap.get("CustomerController"));
//                    activity.startActivity(activity.launcherIntent);
//                }
//
//            }
//        }).setNegativeButton(no, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//
//                dialog.dismiss();
//            }
//        });
//
//        AlertDialog dialog = builder.create();
//
//        dialog.show();
    }

    public void preserveAttributes(List<String> list ) {
Log.v("Info","ENTERING preserve Attributes");
        SharedPreferences sp = activity.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        Set<String> set = new HashSet<>();
        set.addAll(list);
        editor.putStringSet("attributes",set);
        editor.commit();
    }

    public List<String> retrieveAttributes(){
Log.v("Info","ENTERING retrieveAttribute()");
        SharedPreferences sp = activity.getPreferences(Context.MODE_PRIVATE);
        Set<String> set = sp.getStringSet("attributes",null);

        if (set != null){
            Log.v("Info","Set not null");
           List<String> list = new ArrayList<>();
            list.addAll(set);
            return list;
        }
        return null;
    }

//    //gets the channel attribute. defaulting to chat.
//    private void setPositionIntent(int which) {
//        switch (which) {
//            case 0: // chat channel
//                activity.launcherIntent.putExtra("Channel", "Chat");
//
//                break;
//            case 1: // video channel
//                activity.launcherIntent.putExtra("Channel", "Video");
//
//                break;
//
//            default:
//                Log.e("ERROR", "not a recognised chat type choice");
//                break;
//        }
//    }

}
