package org.linphone.bluereach;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;

import org.json.JSONException;
import org.json.JSONObject;
import org.linphone.R;
import org.linphone.bluereach.models.DynviewModel;
import org.linphone.rest.AsyncHttpResponse;
import org.linphone.rest.RestApis;
import org.linphone.utils.AppMethods;
import org.linphone.utils.AppStrings;
import org.linphone.utils.SessionManager;

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

public class ConferencingActivity extends AppCompatActivity implements View.OnClickListener, AsyncHttpResponse.AsyncHttpResponseListener {
    AppCompatEditText guest_pin_et, admin_pin_et, divert1_et, divert2_et, divert3_et, divert4_et, divert5_et;
    LinearLayout disable_conf_ll;
    CheckBox disable_conf_cb;
    Spinner conference_type_sp, turn_num_sp;
    String disable_conf_cb_status = "0", turn_num_sp_status = "0", conference_type_sp_status = "0";
    private static final String TAG = "ConferencingActivity";
    ArrayList<String> conf_room_array;
    ArrayList<String> conf_type_array;
    ArrayList<String> con_id_array;
    ArrayList<String> conference_type_id_array;
    SessionManager sessionManager;
    ImageView back_iv;
    TextView title_tv, product_plus_tv, product_minus_tv;
    ArrayList<DynviewModel> dynArraylist;
    LinearLayout container;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conferencing);
        addView();
        init();
    }

    public void init() {


        conf_room_array = new ArrayList<>();
        conf_type_array = new ArrayList<>();
        con_id_array = new ArrayList<>();
        conference_type_id_array = new ArrayList<>();
        dynArraylist = new ArrayList<>();


        back_iv = (ImageView) findViewById(R.id.back_iv);
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(getResources().getString(R.string.conferencing));
        sessionManager = new SessionManager(ConferencingActivity.this);
        container = (LinearLayout) findViewById(R.id.container);

        guest_pin_et = (AppCompatEditText) findViewById(R.id.guest_pin_et);
        admin_pin_et = (AppCompatEditText) findViewById(R.id.admin_pin_et);
        divert1_et = (AppCompatEditText) findViewById(R.id.divert1_et);
        divert2_et = (AppCompatEditText) findViewById(R.id.divert2_et);
        divert3_et = (AppCompatEditText) findViewById(R.id.divert3_et);
        divert4_et = (AppCompatEditText) findViewById(R.id.divert4_et);
        divert5_et = (AppCompatEditText) findViewById(R.id.divert5_et);
        disable_conf_ll = (LinearLayout) findViewById(R.id.disable_conf_ll);

        disable_conf_cb = (CheckBox) findViewById(R.id.disable_conf_cb);
        conference_type_sp = (Spinner) findViewById(R.id.conference_type_sp);
        turn_num_sp = (Spinner) findViewById(R.id.turn_num_sp);
        product_plus_tv = (TextView) findViewById(R.id.product_plus_tv);
        product_minus_tv = (TextView) findViewById(R.id.product_minus_tv);
        product_plus_tv.setOnClickListener(this);
        product_minus_tv.setOnClickListener(this);


        List<String> conf_room = Arrays.asList(getResources().getStringArray(R.array.conf_room_name));
        List<String> conf_type = Arrays.asList(getResources().getStringArray(R.array.conf_type_name));
        List<String> conf_id = Arrays.asList(getResources().getStringArray(R.array.conference_id));
        List<String> conference_type_id = Arrays.asList(getResources().getStringArray(R.array.conference_type_id));

        for (int i = 0; i < conf_room.size(); i++) {
            conf_room_array.add(conf_room.get(i));
        }
        for (int i = 0; i < conf_type.size(); i++) {
            conf_type_array.add(conf_type.get(i));
        }
        for (int i = 0; i < conf_id.size(); i++) {
            con_id_array.add(conf_id.get(i));
        }
        for (int i = 0; i < conference_type_id.size(); i++) {
            conference_type_id_array.add(conference_type_id.get(i));
        }

        back_iv.setOnClickListener(this);

        disable_conf_ll.setOnClickListener(this);

        disable_conf_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (disable_conf_cb.isPressed()) {
                    if (disable_conf_cb.isChecked()) {

                        disable_conf_cb_status = AppStrings.Constants.on;

                    } else {
                        disable_conf_cb_status = AppStrings.Constants.off;
                    }
                }
            }
        });


        /*Dropdown listenrs*/
        spinnerFunctionality(turn_num_sp, "1", conf_room_array);
        spinnerFunctionality(conference_type_sp, "2", conf_type_array);
        /*performing get Confrence data action here*/
        getConferenceApiCall();

    }

    public void spinnerFunctionality(final Spinner spinner, final String type, final ArrayList<String> array_list) {


        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ConferencingActivity.this, R.layout.custom_spinner, array_list) {
            public View getView(int position, View convertView, ViewGroup parent) {
                View v = super.getView(position, convertView, parent);
                ((TextView) v).setTextColor(getResources().getColor(R.color.light_black));
                ((TextView) v).setBackgroundColor(Color.TRANSPARENT);
                return v;
            }

            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View v = super.getDropDownView(position, convertView, parent);
                v.setBackgroundColor(getResources().getColor(R.color.white));

                ((TextView) v).setGravity(Gravity.LEFT);
                ((TextView) v).setTextColor(getResources().getColor(R.color.light_black));

                return v;
            }


        };

        spinner.setAdapter(arrayAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


                String Text = String.valueOf(spinner.getSelectedItem());


                if (type.equals(AppStrings.Constants.on)) {


                    SettingsId(type, con_id_array.get(position));

                } else if (type.equals(AppStrings.Constants.two)) {

                    SettingsId(type, conference_type_id_array.get(position));
                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    public void SettingsId(String type, String id) {

        if (type.equals("1")) {
            turn_num_sp_status = id;

        } else if (type.equals("2")) {
            conference_type_sp_status = id;

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.disable_conf_ll:
                break;
            case R.id.back_iv:

                /*updating conference data here*/

                String str = "";
                for (int i = 0; i < dynArraylist.size(); i++) {
                    if (str.equals("")) {
                        str = dynArraylist.get(i).getDivert_number();
                    } else {
                        str = str + "\n" + dynArraylist.get(i).getDivert_number();
                    }

                }

                StringBuffer buffer = new StringBuffer(str);
                buffer.reverse();

                updateConferenceApiCall(str);
                break;
            case R.id.product_plus_tv:

           /*adding Numbers diverted to the conference room dynamically*/
                if(container.getChildCount()==0) {
                    addView();
                }
                else {
                    validations(container.getChildCount() - 1);
                }

                break;




            case R.id.product_minus_tv:

                /*removing Numbers diverted to the conference room dynamically*/

                if (container.getChildCount() == 2) {
                    product_minus_tv.setVisibility(View.GONE);
                    container.removeViewAt(container.getChildCount() - 1);
                    dynArraylist.remove(dynArraylist.size() - 1);


                } else {


                    product_minus_tv.setVisibility(View.VISIBLE);
                    container.removeViewAt(container.getChildCount() - 1);
                    dynArraylist.remove(dynArraylist.size() - 1);
                }

                break;
        }
    }

    public void getConferenceApiCall() {


        if (AppMethods.isConnectingToInternet(ConferencingActivity.this)) {
            AsyncHttpResponse response = new AsyncHttpResponse(this, true);
            JSONObject jo = null;
            try {
                jo = new JSONObject();
                jo.put(AppStrings.InputParams.action, RestApis.get_voip_params);
                jo.put(AppStrings.InputParams.login, sessionManager.getStoreData(AppStrings.Session.login));
                jo.put(AppStrings.InputParams.password, sessionManager.getStoreData(AppStrings.Session.password));

                JSONObject job = new JSONObject();
                job.put(AppStrings.Conference.conference_enabled, AppStrings.Conference.conference_enabled);
                job.put(AppStrings.Conference.conference_pin, AppStrings.Conference.conference_pin);
                job.put(AppStrings.Conference.conference_adminpin, AppStrings.Conference.conference_adminpin);
                job.put(AppStrings.Conference.conference_type, AppStrings.Conference.conference_type);
                job.put(AppStrings.Conference.conference_allowed_numbers, AppStrings.Conference.conference_allowed_numbers);
                job.put(AppStrings.Conference.conference_disable_recordings, AppStrings.Conference.conference_disable_recordings);

                jo.put(AppStrings.InputParams.params, job);


            } catch (Exception e) {
                e.printStackTrace();
            }
            response.postJsonAsyncHttp(RestApis.url, RestApis.get_voip_params, jo);
        } else {
            AppMethods.alertForNoInternet(ConferencingActivity.this);
        }
    }

    public void updateConferenceApiCall(String divert_numbers) {


        if (AppMethods.isConnectingToInternet(ConferencingActivity.this)) {
            AsyncHttpResponse response = new AsyncHttpResponse(this, true);
            JSONObject jo = null;
            try {
                jo = new JSONObject();
                jo.put(AppStrings.InputParams.action, RestApis.set_voip_params);
                jo.put(AppStrings.InputParams.login, sessionManager.getStoreData(AppStrings.Session.login));
                jo.put(AppStrings.InputParams.password, sessionManager.getStoreData(AppStrings.Session.password));

                JSONObject job = new JSONObject();
                job.put(AppStrings.Conference.conference_enabled, turn_num_sp_status);
                job.put(AppStrings.Conference.conference_pin, guest_pin_et.getText().toString());
                job.put(AppStrings.Conference.conference_adminpin, admin_pin_et.getText().toString());
                job.put(AppStrings.Conference.conference_type, conference_type_sp_status);
                job.put(AppStrings.Conference.conference_allowed_numbers, divert_numbers);
                job.put(AppStrings.Conference.conference_disable_recordings, disable_conf_cb_status);

                jo.put(AppStrings.InputParams.params, job);


            } catch (Exception e) {
                e.printStackTrace();
            }
            response.postJsonAsyncHttp(RestApis.url, RestApis.set_voip_params, jo);
        } else {
            AppMethods.alertForNoInternet(ConferencingActivity.this);
        }
    }

    @Override
    public void onAsyncHttpResponseGet(String response, String URL) throws JSONException {
        conferenceResponse(response, URL);
    }

    public void conferenceResponse(String response, String url) {
        try {
            JSONObject jo = new JSONObject(response);
            String Status = jo.optString(AppStrings.OutputParams.Status);
            String Message = jo.optString(AppStrings.OutputParams.Message);
            if (Status.equals(AppStrings.OutputParams.Success)) {


                if (url.equals(RestApis.get_voip_params)) {

                    JSONObject job = new JSONObject(jo.getString(AppStrings.InputParams.params));
                    turn_num_sp_status = job.getString(AppStrings.Conference.conference_enabled);
                    guest_pin_et.setText(job.getString(AppStrings.Conference.conference_pin));
                    admin_pin_et.setText(job.getString(AppStrings.Conference.conference_adminpin));
                    conference_type_sp_status = job.getString(AppStrings.Conference.conference_type);
                    String allowed_numbers = job.getString(AppStrings.Conference.conference_allowed_numbers);
                    disable_conf_cb_status = job.getString(AppStrings.Conference.conference_disable_recordings);
                    checkingCheckboxesStatus();


                    for (int i = 0; i < conf_type_array.size(); i++) {
                       if (conference_type_id_array.get(i).equals(conference_type_sp_status)) {
                            conference_type_sp.setSelection(i);

                        }
                    }
                    for (int i = 0; i < conf_room_array.size(); i++) {

                        if (con_id_array.get(i).equals(turn_num_sp_status)) {
                            turn_num_sp.setSelection(i);

                        }
                    }

                    if (!allowed_numbers.equals("") || !allowed_numbers.equals("\\n\\n\\n\\n\\n")) {
                        String[] separated = allowed_numbers.split("\n");


                        if (separated.length != 0) {


                            for (int i = 0; i < separated.length; i++) {

                                if (i != 0) {
                                    product_minus_tv.setVisibility(View.VISIBLE);
                                }
                                addView();
                                dynArraylist.get(i).setBlacklist_number(separated[i]);

                                EditText divert_et = (EditText) container.getChildAt(i).findViewById(R.id.divert_et);

                                divert_et.setText(separated[i]);
                            }

                            setSelectionLength(divert1_et);
                            setSelectionLength(divert2_et);
                            setSelectionLength(divert3_et);
                            setSelectionLength(divert4_et);
                            setSelectionLength(divert5_et);


                        } else {
                            addView();
                        }

                    }


                } else if (url.equals(RestApis.set_voip_params)) {
                    AppMethods.showToast(this, Message);
                    AppMethods.hideSoftKeyboard(this);
                    finish();
                }

            } else {
                AppMethods.showToast(this, Message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void checkingCheckboxesStatus() {

        if (disable_conf_cb_status.equals(AppStrings.Constants.on)) {
            disable_conf_cb.setChecked(true);
        } else {
            disable_conf_cb.setChecked(false);
        }

    }


    public void setSelectionLength(EditText editText) {
        editText.setSelection(editText.getText().length());
    }

    public void validations(int pos) {

        try {
            if (dynArraylist.get(pos).getDivert_number().equals("")) {
                AppMethods.showToast(this, getString(R.string.valid_black_list_number));
            } else {
                product_minus_tv.setVisibility(View.VISIBLE);
                addView();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addView() {

      if(container!=null) {
          Log.e(TAG, "addView: ");
          LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

          View addView = layoutInflater.inflate(R.layout.add_cll_conferencing, null);
          addView.setTag(container.getChildCount());
          init(addView);

          container.addView(addView, container.getChildCount());
          dynArraylist.add(new DynviewModel("", ""));

      }
      else{
          LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          Log.e(TAG, "else block: ");
      }
    }

    public void init(View view) {


        final EditText divert_et = (EditText) view.findViewById(R.id.divert_et);


        TextWatcher textWatcher_quantity = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


                for (int i = 0; i < container.getChildCount(); i++) {

                    if (container.getChildAt(i).findViewById(R.id.divert_et).getTag().toString().equals(divert_et.getTag().toString())) {
                        dynArraylist.get(i).setDivert_number(divert_et.getText().toString());
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        divert_et.addTextChangedListener(textWatcher_quantity);


        divert_et.setTag(container.getChildCount());

    }


}
