package org.linphone.bluereach;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
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.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatSpinner;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentContainerView;
import androidx.fragment.app.FragmentManager;


import org.json.JSONException;
import org.json.JSONObject;
import org.linphone.R;
import org.linphone.activities.main.MainActivity;
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 PbxSettingsFragment extends Fragment implements View.OnClickListener, AsyncHttpResponse.AsyncHttpResponseListener {


    private static final String TAG = "PbxSettingsFragment";
    View view;
    TextView voice_mail_tv, call_forwarding_tv, simultaneous_tv, hunt_group_tv, dnd_tv, caller_id_rejections_tv,
            call_Screening_tv, auto_attendant_tv, caller_id_tv, pin_code_tv, spped_dial_tv, call_rec_tv, conference_tv,
            persnl_info_tv, time_schedle_tv, loc_set_tv, callsettings_tv;
    FragmentContainerView fragnament_container_view;
    ImageView back_iv;
    Spinner profile_spin;
    ArrayList<String> profile_array;
    ArrayList<String> profile_id_array;
    SessionManager sessionManager;
    ArrayAdapter<String> arrayAdapter;
    String location_profiles_disabled, location_profile2_enable = "0",
            location_profile5_longitude, location_profile5_name,
            location_profile4_name, location_profile1_latitude,
            location_profile2_name, location_profile3_enable = "0",
            location_profile2_radius, location_profile5_latitude,
            location_profile1_radius, location_profile2_latitude,
            location_profile3_name, location_profile1_longitude,
            location_profile1_enable = "0", location_profile5_enable = "0",
            location_profile3_longitude, location_profile4_radius,
            location_profile3_latitude, location_profile4_enable = "0",
            location_profile4_longitude, location_profile3_radius,
            location_profile5_radius, location_profile2_longitude,
            location_profile4_latitude, location_profile1_name,
            location_profile_override = "0";
    List<String> profile_names;
    FragmentContainerView i;
    boolean status_click = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_pbx_settings, container, false);
        init();
        return view;
    }

    public void init() {
        /*  *//*** Append the call settings text in tool bar ***//*
        fragnament_container_view = getActivity().findViewById(R.id.status_fragment);
        TextView status_name = fragnament_container_view.findViewById(R.id.status_name);
        TextView settings = fragnament_container_view.findViewById(R.id.settings);
        ImageView status_led = fragnament_containezr_view.findViewById(R.id.status_led);
        status_name.setVisibility(View.GONE);
        status_led.setVisibility(View.GONE);
        settings.setVisibility(View.VISIBLE);*/


        sessionManager = new SessionManager(getActivity());
        profile_array = new ArrayList<>();
        profile_id_array = new ArrayList<>();
        List<String> profile_names_ids = Arrays.asList(getResources().getStringArray(R.array.profile_names_ids));

        for (int i = 0; i < profile_names_ids.size(); i++) {
            profile_id_array.add(profile_names_ids.get(i));
        }
        callsettings_tv = view.findViewById(R.id.callsettings_tv);
        voice_mail_tv = view.findViewById(R.id.voice_mail_tv);
        call_forwarding_tv = view.findViewById(R.id.call_forwarding_tv);
        simultaneous_tv = view.findViewById(R.id.simultaneous_tv);
        hunt_group_tv = view.findViewById(R.id.hunt_group_tv);
        dnd_tv = view.findViewById(R.id.dnd_tv);
        caller_id_rejections_tv = view.findViewById(R.id.caller_id_rejections_tv);
        call_Screening_tv = view.findViewById(R.id.call_Screening_tv);
        auto_attendant_tv = view.findViewById(R.id.auto_attendant_tv);
        caller_id_tv = view.findViewById(R.id.caller_id_tv);
        pin_code_tv = view.findViewById(R.id.pin_code_tv);
        spped_dial_tv = view.findViewById(R.id.spped_dial_tv);
        call_rec_tv = view.findViewById(R.id.call_rec_tv);
        conference_tv = view.findViewById(R.id.conference_tv);
        persnl_info_tv = view.findViewById(R.id.persnl_info_tv);
        time_schedle_tv = view.findViewById(R.id.time_schedle_tv);
        loc_set_tv = view.findViewById(R.id.loc_set_tv);
        profile_spin = view.findViewById(R.id.profile_spin);


        profile_names = new ArrayList<>();

        //spinnerFunctionality(profile_spin);
        LocationSettingsApicall();

        simultaneous_tv.setOnClickListener(this);
        call_forwarding_tv.setOnClickListener(this);
        voice_mail_tv.setOnClickListener(this);
        hunt_group_tv.setOnClickListener(this);
        dnd_tv.setOnClickListener(this);
        caller_id_rejections_tv.setOnClickListener(this);
        call_Screening_tv.setOnClickListener(this);
        auto_attendant_tv.setOnClickListener(this);
        caller_id_tv.setOnClickListener(this);
        pin_code_tv.setOnClickListener(this);
        spped_dial_tv.setOnClickListener(this);
        call_rec_tv.setOnClickListener(this);
        conference_tv.setOnClickListener(this);
        persnl_info_tv.setOnClickListener(this);
        time_schedle_tv.setOnClickListener(this);
        loc_set_tv.setOnClickListener(this);
        callsettings_tv.setOnClickListener(this);


    }

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

                /*Redirection to Call Forward Screen */

                startActivity(new Intent(getActivity(), CallForwardingActivity.class));

                break;
            case R.id.simultaneous_tv:

                /*Redirection to Simultaneous Screen */

                startActivity(new Intent(getActivity(), SimulTaneousActivity.class));

                break;
            case R.id.voice_mail_tv:

                /*Redirection to VoiceMail Screen */

                startActivity(new Intent(getActivity(), VoiceMailsActivity.class));

                break;
            case R.id.hunt_group_tv:

                /*Redirection to HuntGroup Screen */

                startActivity(new Intent(getActivity(), HuntGroupActivity.class));

                break;
            case R.id.dnd_tv:

                /*Redirection to DND Screen based on status */
                callerIdIntent(AppStrings.Constants.dnd);

                break;
            case R.id.caller_id_rejections_tv:

                /*Redirection to caller id rejections Screen based on status */
                startActivity(new Intent(getActivity(), CallerIdRejectionsActivity.class));

                break;
            case R.id.call_Screening_tv:

                /*Redirection to callscreening Screen based on status */

                callerIdIntent(AppStrings.Constants.call_screen);

                break;
            case R.id.auto_attendant_tv:

                /*Redirection to AutoAttendant Screen based on status */

                startActivity(new Intent(getActivity(), AutoAttendantActivity.class));

                break;
            case R.id.caller_id_tv:

                /*Redirection to callerid Screen based on status */

                callerIdIntent(AppStrings.Constants.call_id_priv);

                break;
            case R.id.pin_code_tv:

                /*Redirection to pincode Screen based on status */
                callerIdIntent(AppStrings.Constants.pincode);

                break;
            case R.id.spped_dial_tv:

                /*Redirection to speed dial Screen */

                startActivity(new Intent(getActivity(), SpeedDialActivity.class));

                break;
            case R.id.call_rec_tv:

                /*Redirection to Call Recording Screen */

                startActivity(new Intent(getActivity(), CallRecordActivity.class));

                break;
            case R.id.conference_tv:

                /*Redirection to Conference Screen based on status */

                startActivity(new Intent(getActivity(), ConferencingActivity.class));

                break;
            case R.id.persnl_info_tv:

                /*Redirection to Personal Screen based on status */

                callerIdIntent(AppStrings.Constants.personal);

                break;
            case R.id.time_schedle_tv:

                /*Redirection to timeSchedule Screen based on status */

                startActivity(new Intent(getActivity(), TimeScheduleActivity.class));

                break;
            case R.id.loc_set_tv:
                /*Redirection to timeSchedule Screen based on status */
                startActivity(new Intent(getActivity(), LocationSettingsActivity.class));
                break;
            case R.id.callsettings_tv:
//                findNavController().popBackStack()

        }
    }

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


        if (URL.equals(RestApis.get_voip_params)) {
            getLocationSettingsResponse(response, RestApis.get_voip_params);
        } else if (URL.equals(RestApis.set_voip_params)) {
            getLocationSettingsResponse(response, RestApis.set_voip_params);
        }

    }

    public void callerIdIntent(String status) {

        Intent intent = new Intent(getActivity(), CallIdScreeningPinCodeDndPersInfoActivity.class);
        intent.putExtra(AppStrings.IntentData.redirection_status, status);
        startActivity(intent);
    }

    public void spinnerFunctionality(final Spinner spinner) {

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

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


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


                if (status_click) {
                    location_profile_override = profile_id_array.get(position);
                    updateLocationSettingsApicall(profile_id_array.get(position));
                }


            }

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

            }
        });

    }

    public void LocationSettingsApicall() {

        if (AppMethods.isConnectingToInternet(getActivity())) {
            AsyncHttpResponse response = new AsyncHttpResponse(this, false);
            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));
                jo.put(AppStrings.InputParams.profile, AppStrings.Constants.default_profile);

                JSONObject job = new JSONObject();


                job.put(AppStrings.LocationSettings.location_profile_override, AppStrings.LocationSettings.location_profile_override);
                job.put(AppStrings.LocationSettings.location_profiles_disabled, AppStrings.LocationSettings.location_profiles_disabled);
                job.put(AppStrings.LocationSettings.location_profile1_enable, AppStrings.LocationSettings.location_profile1_enable);
                job.put(AppStrings.LocationSettings.location_profile1_name, AppStrings.LocationSettings.location_profile1_name);
                job.put(AppStrings.LocationSettings.location_profile1_radius, AppStrings.LocationSettings.location_profile1_radius);
                job.put(AppStrings.LocationSettings.location_profile1_longitude, AppStrings.LocationSettings.location_profile1_longitude);
                job.put(AppStrings.LocationSettings.location_profile1_latitude, AppStrings.LocationSettings.location_profile1_latitude);

                job.put(AppStrings.LocationSettings.location_profile2_enable, AppStrings.LocationSettings.location_profile2_enable);
                job.put(AppStrings.LocationSettings.location_profile2_name, AppStrings.LocationSettings.location_profile2_name);
                job.put(AppStrings.LocationSettings.location_profile2_radius, AppStrings.LocationSettings.location_profile2_radius);
                job.put(AppStrings.LocationSettings.location_profile2_longitude, AppStrings.LocationSettings.location_profile2_longitude);
                job.put(AppStrings.LocationSettings.location_profile2_latitude, AppStrings.LocationSettings.location_profile2_latitude);

                job.put(AppStrings.LocationSettings.location_profile3_enable, AppStrings.LocationSettings.location_profile3_enable);
                job.put(AppStrings.LocationSettings.location_profile3_name, AppStrings.LocationSettings.location_profile3_name);
                job.put(AppStrings.LocationSettings.location_profile3_radius, AppStrings.LocationSettings.location_profile3_radius);
                job.put(AppStrings.LocationSettings.location_profile3_longitude, AppStrings.LocationSettings.location_profile3_longitude);
                job.put(AppStrings.LocationSettings.location_profile3_latitude, AppStrings.LocationSettings.location_profile3_latitude);

                job.put(AppStrings.LocationSettings.location_profile4_enable, AppStrings.LocationSettings.location_profile4_enable);
                job.put(AppStrings.LocationSettings.location_profile4_name, AppStrings.LocationSettings.location_profile4_name);
                job.put(AppStrings.LocationSettings.location_profile4_radius, AppStrings.LocationSettings.location_profile4_radius);
                job.put(AppStrings.LocationSettings.location_profile4_longitude, AppStrings.LocationSettings.location_profile4_longitude);
                job.put(AppStrings.LocationSettings.location_profile4_latitude, AppStrings.LocationSettings.location_profile4_latitude);

                job.put(AppStrings.LocationSettings.location_profile5_enable, AppStrings.LocationSettings.location_profile5_enable);
                job.put(AppStrings.LocationSettings.location_profile5_name, AppStrings.LocationSettings.location_profile5_name);
                job.put(AppStrings.LocationSettings.location_profile5_radius, AppStrings.LocationSettings.location_profile5_radius);
                job.put(AppStrings.LocationSettings.location_profile5_longitude, AppStrings.LocationSettings.location_profile5_longitude);
                job.put(AppStrings.LocationSettings.location_profile5_latitude, AppStrings.LocationSettings.location_profile5_latitude);
                jo.put(AppStrings.InputParams.params, job);


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

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

                    location_profile_override = job.getString(AppStrings.LocationSettings.location_profile_override);

                    location_profiles_disabled = job.getString(AppStrings.LocationSettings.location_profiles_disabled);


                    location_profile1_latitude = job.getString(AppStrings.LocationSettings.location_profile1_latitude);
                    location_profile1_radius = job.getString(AppStrings.LocationSettings.location_profile1_radius);
                    location_profile1_longitude = job.getString(AppStrings.LocationSettings.location_profile1_longitude);
                    location_profile1_enable = job.getString(AppStrings.LocationSettings.location_profile1_enable);
                    location_profile1_name = job.getString(AppStrings.LocationSettings.location_profile1_name);


                    location_profile2_name = job.getString(AppStrings.LocationSettings.location_profile2_name);
                    location_profile2_radius = job.getString(AppStrings.LocationSettings.location_profile2_radius);
                    location_profile2_latitude = job.getString(AppStrings.LocationSettings.location_profile2_latitude);
                    location_profile2_longitude = job.getString(AppStrings.LocationSettings.location_profile2_longitude);
                    location_profile2_enable = job.getString(AppStrings.LocationSettings.location_profile2_enable);


                    location_profile3_name = job.getString(AppStrings.LocationSettings.location_profile3_name);
                    location_profile3_longitude = job.getString(AppStrings.LocationSettings.location_profile3_longitude);
                    location_profile3_latitude = job.getString(AppStrings.LocationSettings.location_profile3_latitude);
                    location_profile3_radius = job.getString(AppStrings.LocationSettings.location_profile3_radius);
                    location_profile3_enable = job.getString(AppStrings.LocationSettings.location_profile3_enable);


                    location_profile4_name = job.getString(AppStrings.LocationSettings.location_profile4_name);
                    location_profile4_radius = job.getString(AppStrings.LocationSettings.location_profile4_radius);
                    location_profile4_enable = job.getString(AppStrings.LocationSettings.location_profile4_enable);
                    location_profile4_longitude = job.getString(AppStrings.LocationSettings.location_profile4_longitude);
                    location_profile4_latitude = job.getString(AppStrings.LocationSettings.location_profile4_latitude);

                    location_profile5_latitude = job.getString(AppStrings.LocationSettings.location_profile5_latitude);
                    location_profile5_enable = job.getString(AppStrings.LocationSettings.location_profile5_enable);
                    location_profile5_longitude = job.getString(AppStrings.LocationSettings.location_profile5_longitude);
                    location_profile5_name = job.getString(AppStrings.LocationSettings.location_profile5_name);
                    location_profile5_radius = job.getString(AppStrings.LocationSettings.location_profile5_radius);

                    profile_names.clear();
                    profile_names.add(getString(R.string.auto));
                    profile_names.add(getString(R.string.defa));
                    profile_names.add(location_profile1_name);
                    profile_names.add(location_profile2_name);
                    profile_names.add(location_profile3_name);
                    profile_names.add(location_profile4_name);
                    profile_names.add(location_profile5_name);


                    for (int i = 0; i < profile_names.size(); i++) {
                        profile_array.add(profile_names.get(i));
                    }


                    spinnerFunctionality(profile_spin);
                    if (!(location_profile_override.equals("0") || location_profile_override.equals(""))) {

                        if (location_profile_override.equals("-1")) {
                            profile_spin.setSelection(1);
                        } else {
                            int loc_ovr = job.getInt(AppStrings.LocationSettings.location_profile_override);
                            profile_spin.setSelection((loc_ovr + 1));
                        }

                    } else {
                        location_profile_override = "0";
                        int loc_ovr = Integer.parseInt(location_profile_override);
                        profile_spin.setSelection((loc_ovr));
                    }

                    arrayAdapter.notifyDataSetChanged();


                } else if (url.equals(RestApis.set_voip_params)) {
                    AppMethods.hideSoftKeyboard(getActivity());
                }

                status_click = true;

            } else {
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateLocationSettingsApicall(String val) {

        if (AppMethods.isConnectingToInternet(getActivity())) {
            AsyncHttpResponse response = new AsyncHttpResponse(this, false);
            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));
                jo.put(AppStrings.InputParams.profile, AppStrings.Constants.default_profile);

                JSONObject job = new JSONObject();

                job.put(AppStrings.LocationSettings.location_profile_override, val);
                jo.put(AppStrings.InputParams.params, job);


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

}
