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.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 CallRecordActivity extends AppCompatActivity implements View.OnClickListener, AsyncHttpResponse.AsyncHttpResponseListener {

    private static final String TAG = "CallRecordActivity";
    ArrayList<String> call_rec_option_name_array;
    ArrayList<String> call_rec_option_id_array;
    ArrayList<String> call_rec_direction_name_array;
    ArrayList<String> call_rec_direction_id_array;
    CheckBox disable_recording_cb, send_copy_cb;
    String send_copy_cb_status = "0", disable_recording_cb_status = "0", recording_options_sp_status = "", call_recording_dir_sp_status = "";
    Spinner recording_options_sp, call_recording_dir_sp;
    SessionManager sessionManager;
    AppCompatEditText alter_eamil_et;
            EditText numbers_enabled_et;

    ImageView back_iv;
    TextView title_tv, product_plus_tv, product_minus_tv;
    LinearLayout container;
    ArrayList<DynviewModel> dynArraylist;

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

    public void init() {

        sessionManager = new SessionManager(this);

        call_rec_option_name_array = new ArrayList<String>();
        call_rec_option_id_array = new ArrayList<String>();
        call_rec_direction_name_array = new ArrayList<String>();
        call_rec_direction_id_array = new ArrayList<String>();

        dynArraylist = new ArrayList<>();

        container = (LinearLayout) findViewById(R.id.container);
        back_iv = (ImageView) findViewById(R.id.back_iv);
        title_tv = (TextView) findViewById(R.id.title_tv);

        title_tv.setText(getResources().getString(R.string.call_recording));


        disable_recording_cb = (CheckBox) findViewById(R.id.disable_recording_cb);
        send_copy_cb = (CheckBox) findViewById(R.id.send_copy_cb);

        recording_options_sp = (Spinner) findViewById(R.id.recording_options_sp);
        call_recording_dir_sp = (Spinner) findViewById(R.id.call_recording_dir_sp);
        alter_eamil_et = (AppCompatEditText) findViewById(R.id.alter_eamil_et);
        numbers_enabled_et = (EditText) findViewById(R.id.numbers_enabled_et);
        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> recording_otp_name = Arrays.asList(getResources().getStringArray(R.array.recording_otp_name));
        List<String> recording_option_id = Arrays.asList(getResources().getStringArray(R.array.recording_option_id));
        List<String> recording_direction_name = Arrays.asList(getResources().getStringArray(R.array.recording_direction_name));
        List<String> rec_direction_id = Arrays.asList(getResources().getStringArray(R.array.rec_direction_id));

        for (int i = 0; i < recording_otp_name.size(); i++) {
            call_rec_option_name_array.add(recording_otp_name.get(i));

        }
        for (int i = 0; i < recording_option_id.size(); i++) {
            call_rec_option_id_array.add(recording_option_id.get(i));
        }
        for (int i = 0; i < recording_direction_name.size(); i++) {
            call_rec_direction_name_array.add(recording_direction_name.get(i));
        }
        for (int i = 0; i < rec_direction_id.size(); i++) {
            call_rec_direction_id_array.add(rec_direction_id.get(i));
        }


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

                    if (disable_recording_cb.isChecked()) {
                        disable_recording_cb_status = AppStrings.Constants.on;
                    } else {
                        disable_recording_cb_status = AppStrings.Constants.off;
                    }
                }
            }
        });
        send_copy_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (send_copy_cb.isPressed()) {
                    if (send_copy_cb.isChecked()) {
                        send_copy_cb_status = AppStrings.Constants.on;
                    } else {
                        send_copy_cb_status = AppStrings.Constants.off;
                    }
                }
            }
        });

        back_iv.setOnClickListener(this);

        spinnerFunctionality(recording_options_sp, "1", call_rec_option_name_array);
        spinnerFunctionality(call_recording_dir_sp, "2", call_rec_direction_name_array);

        getCallRecordingsApicall();


    }

    public void spinnerFunctionality(final Spinner spinner, final String type, final ArrayList arrayList) {


        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(CallRecordActivity.this, R.layout.custom_spinner, arrayList) {
            public View getView(int position, View convertView, ViewGroup parent) {
                View v = super.getView(position, convertView, parent);
                ((TextView) v).setTextColor(getResources().getColor(R.color.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);

                return v;
            }


        };

        spinner.setAdapter(arrayAdapter);
//        arrayAdapter.setDropDownViewResource(R.layout.spinner_custom_layout);

        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)) {
                    if (Text.equals("Disable Call Recording")) {


                        SettingsId(type, call_rec_option_id_array.get(0));
                    } else {

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

                } else if (type.equals(AppStrings.Constants.two)) {
                    if (Text.equals("Call Recording Direction")) {


                        SettingsId(type, call_rec_direction_id_array.get(0));
                    } else {

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


            }

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

            }
        });

    }

    public void SettingsId(String type, String id) {

        if (type.equals(AppStrings.Constants.on)) {
            recording_options_sp_status = id;

        } else if (type.equals(AppStrings.Constants.two)) {
            call_recording_dir_sp_status = id;

        }

    }


    public void updateCallRecordingsApicall(String enabled_numbers) {

        if (AppMethods.isConnectingToInternet(CallRecordActivity.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.CallRecordings.callrecording_disabled, disable_recording_cb_status);
                job.put(AppStrings.CallRecordings.callrecording_type, recording_options_sp_status);
//                job.put(AppStrings.CallRecordings.callrecording_allowed_numbers, numbers_enabled_et.getText().toString());
                job.put(AppStrings.CallRecordings.callrecording_allowed_numbers, enabled_numbers);
                job.put(AppStrings.CallRecordings.callrecording_emailcopy, send_copy_cb_status);
                job.put(AppStrings.CallRecordings.callrecording_alternativeemail, alter_eamil_et.getText().toString());
                job.put(AppStrings.CallRecordings.callrecording_direction, call_recording_dir_sp_status);

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


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

    public void getCallRecordingsApicall() {


        if (AppMethods.isConnectingToInternet(CallRecordActivity.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.CallRecordings.callrecording_disabled, AppStrings.CallRecordings.callrecording_disabled);
                job.put(AppStrings.CallRecordings.callrecording_type, AppStrings.CallRecordings.callrecording_type);
                job.put(AppStrings.CallRecordings.callrecording_allowed_numbers, AppStrings.CallRecordings.callrecording_allowed_numbers);
                job.put(AppStrings.CallRecordings.callrecording_emailcopy, AppStrings.CallRecordings.callrecording_emailcopy);
                job.put(AppStrings.CallRecordings.callrecording_alternativeemail, AppStrings.CallRecordings.callrecording_alternativeemail);
                job.put(AppStrings.CallRecordings.callrecording_direction, AppStrings.CallRecordings.callrecording_direction);

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


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

    public void callRecordingResponse(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));


                    disable_recording_cb_status = job.getString(AppStrings.CallRecordings.callrecording_disabled);
                    recording_options_sp_status = job.getString(AppStrings.CallRecordings.callrecording_type);
                    call_recording_dir_sp_status = job.getString(AppStrings.CallRecordings.callrecording_direction);
                    numbers_enabled_et.setText(job.getString(AppStrings.CallRecordings.callrecording_allowed_numbers));
                    send_copy_cb_status = job.getString(AppStrings.CallRecordings.callrecording_emailcopy);
                    alter_eamil_et.setText(job.getString(AppStrings.CallRecordings.callrecording_alternativeemail));

                    String numbers_enabled = job.getString(AppStrings.CallRecordings.callrecording_allowed_numbers);
                    checkingCheckboxesStatus();


                    for (int i = 0; i < call_rec_direction_name_array.size(); i++) {
                        if (call_rec_direction_id_array.get(i).equals(call_recording_dir_sp_status)) {
                            call_recording_dir_sp.setSelection(i);
                        }

                    }
                    for (int i = 0; i < call_rec_option_name_array.size(); i++) {
                        if (call_rec_option_id_array.get(i).equals(recording_options_sp_status)) {
                            recording_options_sp.setSelection(i);
                        }

                    }

                    numbers_enabled_et.setSelection(numbers_enabled_et.getText().length());
                    alter_eamil_et.setSelection(alter_eamil_et.getText().length());


                    if (!numbers_enabled.equals("") || !numbers_enabled.equals("\\n\\n\\n\\n\\n")) {
                        String[] separated = numbers_enabled.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 numbers_enabled_dyn_et = (EditText) container.getChildAt(i).findViewById(R.id.numbers_enabled_dyn_et);

                                numbers_enabled_dyn_et.setText(separated[i]);
                            }


                        } else {
                            addView();
                        }

                    }


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

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

    }


    public void checkingCheckboxesStatus() {

        if (disable_recording_cb_status.equals(AppStrings.Constants.on)) {
            disable_recording_cb.setChecked(true);
        } else {
            disable_recording_cb.setChecked(false);
        }
        if (send_copy_cb_status.equals(AppStrings.Constants.on)) {
            send_copy_cb.setChecked(true);
        } else {
            send_copy_cb.setChecked(false);
        }

    }


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


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

                }

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


                updateCallRecordingsApicall(str);

                break;
            case R.id.product_plus_tv:
                if(container.getChildCount()==0) {
                    addView();
                }
                else {
                    validations(container.getChildCount() - 1);
                }

                break;


            case R.id.product_minus_tv:
                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;

        }

    }

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

    public void validations(int pos) {

        try {
            if (dynArraylist.get(pos).getNumbers_enabled().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() {

        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

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

        container.addView(addView, container.getChildCount());


        dynArraylist.add(new DynviewModel("", "", ""));


    }

    public void init(View view) {


        final EditText numbers_enabled_dyn_et = (EditText) view.findViewById(R.id.numbers_enabled_dyn_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.numbers_enabled_dyn_et).getTag().toString().equals(numbers_enabled_dyn_et.getTag().toString())) {
                        dynArraylist.get(i).setNumbers_enabled(numbers_enabled_dyn_et.getText().toString());
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        numbers_enabled_dyn_et.addTextChangedListener(textWatcher_quantity);


        numbers_enabled_dyn_et.setTag(container.getChildCount());

    }

}
