package org.linphone.bluereach;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

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;

public class CallerIdRejectionsActivity extends AppCompatActivity implements View.OnClickListener, AsyncHttpResponse.AsyncHttpResponseListener {

    EditText blacklisted_one_et, blacklisted_two_et, blacklisted_three_et, blacklisted_four_et, blacklisted_five_et;
    CheckBox disable_waiting_cb, reject_calls_cb;


    String disable_waiting_cb_status = "0", reject_calls_cb_status = "0";
    SessionManager sessionManager;
    ImageView back_iv;
    TextView title_tv, product_plus_tv, product_minus_tv;
    LinearLayout container;
    ArrayList<DynviewModel> dynArraylist;
    String black_list = "";
    private static final String TAG = "CallerIdRejectionsActiv";

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

    public void init() {
        dynArraylist = new ArrayList<>();
        sessionManager = new SessionManager(this);

        back_iv = (ImageView) findViewById(R.id.back_iv);
        product_plus_tv = (TextView) findViewById(R.id.product_plus_tv);
        product_minus_tv = (TextView) findViewById(R.id.product_minus_tv);
        container = (LinearLayout) findViewById(R.id.container);
        ;
        blacklisted_one_et = (EditText) findViewById(R.id.blacklisted_one_et);
        blacklisted_two_et = (EditText) findViewById(R.id.blacklisted_two_et);
        blacklisted_three_et = (EditText) findViewById(R.id.blacklisted_three_et);
        blacklisted_four_et = (EditText) findViewById(R.id.blacklisted_four_et);
        blacklisted_five_et = (EditText) findViewById(R.id.blacklisted_five_et);
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(getResources().getString(R.string.callerid_rejections));
        disable_waiting_cb = (CheckBox) findViewById(R.id.disable_waiting_cb);
        reject_calls_cb = (CheckBox) findViewById(R.id.reject_calls_cb);
        back_iv.setOnClickListener(this);
        product_plus_tv.setOnClickListener(this);
        product_minus_tv.setOnClickListener(this);


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

                    if (disable_waiting_cb.isChecked()) {
                        disable_waiting_cb_status = AppStrings.Constants.on;
                    } else {
                        disable_waiting_cb_status = AppStrings.Constants.off;
                    }
                }
            }
        });

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

                    if (reject_calls_cb.isChecked()) {
                        reject_calls_cb_status = AppStrings.Constants.on;
                    } else {
                        reject_calls_cb_status = AppStrings.Constants.off;
                    }
                }
            }
        });


//        addView();
        getCallerIdRejectionsApicall();


    }

    public void getCallerIdRejectionsApicall() {

        if (AppMethods.isConnectingToInternet(CallerIdRejectionsActivity.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.callaerRejections.call_waiting_disable, AppStrings.callaerRejections.call_waiting_disable);
                job.put(AppStrings.callaerRejections.anoncall_reject, AppStrings.callaerRejections.anoncall_reject);
                job.put(AppStrings.callaerRejections.blacklist, AppStrings.callaerRejections.blacklist);

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


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

    public void updateCallerIdRejectionsApicall(String str) {



        if (AppMethods.isConnectingToInternet(CallerIdRejectionsActivity.this)) {
            Log.e(TAG, "updateCallerIdRejectionsApicall: "+str );
            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.callaerRejections.call_waiting_disable, disable_waiting_cb_status);
                job.put(AppStrings.callaerRejections.anoncall_reject, reject_calls_cb_status);
                job.put(AppStrings.callaerRejections.blacklist, str);

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


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

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_iv:
                Log.e(TAG, "onClick:back " );

                String str = "";
                for (int i = 0; i < dynArraylist.size(); i++) {

                    if (str.equals("")) {
                        str = dynArraylist.get(i).getBlacklist_number();
                    } else {
                        str = str + "\n" + dynArraylist.get(i).getBlacklist_number();
                    }

                }

                updateCallerIdRejectionsApicall(str);


                break;
            case R.id.product_plus_tv:
                Log.e(TAG, "onClick:getChildCount "+container.getChildCount() );
                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(container.getChildCount());


                } else {


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

                break;
        }
    }

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


    public void validations(int pos) {
        if (dynArraylist.get(pos).getBlacklist_number().equals("")) {
            AppMethods.showToast(this, getString(R.string.valid_black_list_number));
        } else {
            product_minus_tv.setVisibility(View.VISIBLE);
            addView();
        }
    }


    public void rejectionsResponse(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));
                    reject_calls_cb_status = job.getString(AppStrings.callaerRejections.anoncall_reject);
                    disable_waiting_cb_status = job.getString(AppStrings.callaerRejections.call_waiting_disable);
                    String blacklist = job.getString(AppStrings.callaerRejections.blacklist);
                    checkingCheckboxesStatus();
                    if (!blacklist.equals("")) {


                        String[] separated = blacklist.split("\n");


                        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 blacklisted_et = (EditText) container.getChildAt(i).findViewById(R.id.blacklisted_et);

                            blacklisted_et.setText(separated[i]);
                        }


                        blacklisted_one_et.setSelection(blacklisted_one_et.getText().length());
                        blacklisted_two_et.setSelection(blacklisted_two_et.getText().length());
                        blacklisted_three_et.setSelection(blacklisted_three_et.getText().length());
                        blacklisted_four_et.setSelection(blacklisted_four_et.getText().length());
                        blacklisted_five_et.setSelection(blacklisted_five_et.getText().length());

                    } 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 (reject_calls_cb_status.equals(AppStrings.Constants.on)) {
            reject_calls_cb.setChecked(true);
        } else {
            reject_calls_cb.setChecked(false);
        }
        if (disable_waiting_cb_status.equals(AppStrings.Constants.on)) {
            disable_waiting_cb.setChecked(true);
        } else {
            disable_waiting_cb.setChecked(false);
        }

    }

    public void addView() {

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

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

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


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


    }

    public void init(View view) {


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

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        blacklisted_et.addTextChangedListener(textWatcher_quantity);


        blacklisted_et.setTag(container.getChildCount());

    }

}
