package com.ttiglobal.inttilectgpchat.training.activities;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ttiglobal.inttilectgpchat.AMHomeActivity;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.training.utils.MultiSelectSpinner;
import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MainApplication;
import com.ttiglobal.inttilectgpchat.util.TransparentProgressDialog;
import com.ttiglobal.inttilectgpchat.util.UtilService;
import com.ttiglobal.inttilectgpchat.wrappers.AMResponse;
import com.ttiglobal.inttilectgpchat.wrappers.CommonResponse;
import com.ttiglobal.inttilectgpchat.wrappers.DSE;
import com.ttiglobal.inttilectgpchat.wrappers.DSEResponse;
import com.ttiglobal.inttilectgpchat.wrappers.DealerResponse;
import com.ttiglobal.inttilectgpchat.wrappers.ErrorResponse;
import com.ttiglobal.inttilectgpchat.wrappers.RMResponse;
import com.ttiglobal.inttilectgpchat.wrappers.Title;
import com.ttiglobal.inttilectgpchat.wrappers.TitleResponse;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.wdullaer.materialdatetimepicker.time.Timepoint;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ScheduleActivity extends AppCompatActivity {

    private TextView fromTime;
    private TextView toTime;
    private MultiSelectSpinner regionSpinner, areaSpinner, dealerSpinner, dseSpinner;
    private TextView dateSelection;
    private TextView title;
    private EditText description;

    private TransparentProgressDialog progressDialog;

    private ApiService restService;

    private String[] nameList = {"Select"};

    private String[] mDSEList = {"Select"};
    private String[] mDSEId = {"-1"};

    private String[] mRegionList = {"Select"};
    private String[] mRegionId = {"-1"};

    private String[] mAMList = {"Select"};
    private String[] mAMId = {"-1"};

    private String[] mDealerList = {"Select"};
    private String[] items = {"None"};
    private String[] mDealerId = {"-1"};

    private List<Integer> NAMES = new ArrayList<>();

    private ArrayList<DSE> DSE_LIST = new ArrayList<>();

    private Calendar myCalendar = Calendar.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private PartiPantAdapter adapter;
    private ArrayList<Title> TITLES = new ArrayList<>();
    private LinearLayout llout_region, llout_am, llout_dealer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);
        setupWindowAnimations();
        restService = ((MainApplication) getApplication()).getClient();

        fromTime = findViewById(R.id.fromTime);
        toTime = findViewById(R.id.toTime);
        regionSpinner = findViewById(R.id.regionSpinner);
        areaSpinner = findViewById(R.id.areaSpinner);
        dealerSpinner = findViewById(R.id.dealerSpinner);
        dseSpinner = findViewById(R.id.dseSpinner);
        GridView participantList = findViewById(R.id.participantList);
        adapter = new PartiPantAdapter();
        participantList.setAdapter(adapter);
        llout_region = findViewById(R.id.llout_region);
        llout_am = findViewById(R.id.llout_am);
        llout_dealer = findViewById(R.id.llout_dealer);

        dateSelection = findViewById(R.id.dateSelection);
        title = findViewById(R.id.title);
        description = findViewById(R.id.description);
        Button schedule = findViewById(R.id.schedule);

        title.setOnClickListener(view -> {
            int selection = 0;
            if (!title.getText().toString().isEmpty()) {
                selection = Arrays.asList(items).indexOf(title.getText().toString().trim());
            }
            new AlertDialog.Builder(ScheduleActivity.this)
                    .setSingleChoiceItems(items, selection, null)
                    .setNegativeButton("Cancel", null)
                    .setPositiveButton("Ok", (dialog, whichButton) -> {
                        dialog.dismiss();
                        int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                        title.setText(items[selectedPosition]);
                    })
                    .show();
        });


        findViewById(R.id.levelSpinner).setOnClickListener(view -> title.performClick());

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        Objects.requireNonNull(getSupportActionBar()).setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
          backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
          getSupportActionBar().setHomeAsUpIndicator(backArrow);

        regionSpinner.setItems(nameList);
        areaSpinner.setItems(nameList);
        dealerSpinner.setItems(nameList);
        dseSpinner.setItems(nameList);

        regionSpinner.setTitle("Select Regional Manager");
        areaSpinner.setTitle("Select Area Manager");
        dealerSpinner.setTitle("Select Dealer");
        dseSpinner.setTitle("Select DSE");

        myCalendar = Calendar.getInstance();
        dateSelection.setText(sdf.format(myCalendar.getTime()));

        regionSpinner.setListener(new MultiSelectSpinner.OnMultipleItemsSelectedListener() {
            @Override
            public void selectedIndices(List<Integer> indices) {
                areaSpinner.setItems(nameList);
                dealerSpinner.setItems(nameList);
                dseSpinner.setItems(nameList);
                NAMES = new ArrayList<>();
                adapter.notifyDataSetChanged();
                if (indices.size() != 0 && indices.get(0) != 0) {
                    ArrayList<String> rmList = new ArrayList<>();
                    for (int i = 0; i < indices.size(); i++) {
                        rmList.add(mRegionId[indices.get(i)]);
                    }
                    getAMDetails(rmList);
                }
            }

            @Override
            public void selectedStrings(List<String> strings) {

            }
        });

        areaSpinner.setListener(new MultiSelectSpinner.OnMultipleItemsSelectedListener() {
            @Override
            public void selectedIndices(List<Integer> indices) {
                dealerSpinner.setItems(nameList);
                dseSpinner.setItems(nameList);
                NAMES = new ArrayList<>();
                adapter.notifyDataSetChanged();
                if (indices.size() != 0 && indices.get(0) != 0) {
                    ArrayList<String> amList = new ArrayList<>();
                    for (int i = 0; i < indices.size(); i++) {
                        amList.add(mAMId[indices.get(i)]);
                    }
                    getDealerDetails(amList);
                }
            }

            @Override
            public void selectedStrings(List<String> strings) {

            }
        });

        dealerSpinner.setListener(new MultiSelectSpinner.OnMultipleItemsSelectedListener() {
            @Override
            public void selectedIndices(List<Integer> indices) {
                dseSpinner.setItems(nameList);
                NAMES = new ArrayList<>();
                adapter.notifyDataSetChanged();
                if (indices.size() != 0 && indices.get(0) != 0) {
                    ArrayList<String> dealerList = new ArrayList<>();
                    for (int i = 0; i < indices.size(); i++) {
                        dealerList.add(mDealerId[indices.get(i)]);
                    }
                    getDSEDetails(dealerList);
                }
            }

            @Override
            public void selectedStrings(List<String> strings) {

            }
        });

        dseSpinner.setListener(new MultiSelectSpinner.OnMultipleItemsSelectedListener() {
            @Override
            public void selectedIndices(List<Integer> indices) {
                if (indices.size() != 0 && indices.get(0) != 0) {
                    NAMES = indices;
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void selectedStrings(List<String> strings) {

            }
        });

        fromTime.setOnClickListener(view -> {
            try {
                TimePickerDialog timePicker = TimePickerDialog.newInstance((view12, hourOfDay, minute, second) -> {
                    String hour = (hourOfDay > 9) ? String.valueOf(hourOfDay) : "0" + hourOfDay;
                    String min = (minute > 9) ? String.valueOf(minute) : "0" + minute;
                    fromTime.setText(String.format("%s:%s", hour, min));
                    toTime.setText("");
                }, false);
                timePicker.setSelectableTimes(generateTimepoints(5));

                if (dateSelection.getText().toString().trim().equalsIgnoreCase(sdf.format(new Date()))) {
                    SimpleDateFormat format = new SimpleDateFormat("HH", Locale.getDefault());
                    int hour = Integer.parseInt(format.format(Objects.requireNonNull(new Date())));
                    format = new SimpleDateFormat("mm", Locale.getDefault());
                    int minutes = Integer.parseInt(format.format(new Date()));
                    int x = minutes % 5;
                    if (x > 0) {
                        int y = minutes / 5;
                        minutes = (y + 1) * 5;
                        if (minutes >= 60) {
                            hour = hour + 1;
                        }
                    }
                    timePicker.setInitialSelection(hour, minutes);
                    timePicker.setMinTime(hour, minutes, 0);
                } else {
                    timePicker.setInitialSelection(0, 0);
                }
                timePicker.show(getSupportFragmentManager(), "TimePickerDialog");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        toTime.setOnClickListener(view -> {
            try {
                if (fromTime.getText().toString().trim().isEmpty()) {
                    Toast.makeText(this, "Please select from time", Toast.LENGTH_SHORT).show();
                    return;
                }

                TimePickerDialog timePicker = TimePickerDialog.newInstance((view1, hourOfDay, minute, second) -> {
                    String hour = (hourOfDay > 9) ? String.valueOf(hourOfDay) : "0" + hourOfDay;
                    String min = (minute > 9) ? String.valueOf(minute) : "0" + minute;
                    toTime.setText(String.format("%s:%s", hour, min));
                }, false);
                timePicker.setSelectableTimes(generateTimepoints(5));

                String[] mTime = fromTime.getText().toString().trim().split(":");
                int hour = Integer.parseInt(mTime[0]);
                int minutes = Integer.parseInt(mTime[1]) + 5;

                if (minutes >= 60) {
                    hour = hour + 1;
                }

                timePicker.setInitialSelection(hour, minutes);
                timePicker.setMinTime(hour, minutes, 0);
                timePicker.show(getSupportFragmentManager(), "TimePickerDialog");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        dateSelection.setOnClickListener(v -> {
            DatePickerDialog dialog = new DatePickerDialog(ScheduleActivity.this, dateSetListener, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH));
            dialog.getDatePicker().setMinDate(System.currentTimeMillis());
            dialog.show();
        });

        if (!GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
            if (!GlobalData.user.getData().getRole().equalsIgnoreCase("7")) {
                if (!GlobalData.user.getData().getRole().equalsIgnoreCase("14")) {
                    getRMDetails();
                } else {
                    mDealerList[0] = GlobalData.user.getData().getName();
                    mDealerId[0] = GlobalData.user.getData().getDealer().getDealer_code();

                    llout_region.setVisibility(View.GONE);
                    llout_am.setVisibility(View.GONE);
                    llout_dealer.setVisibility(View.GONE);

                    dseSpinner.setItems(nameList);
                    NAMES = new ArrayList<>();
                    adapter.notifyDataSetChanged();
                    ArrayList<String> dealerList = new ArrayList<>();
                    dealerList.add(mDealerId[0]);
                    getDSEDetails(dealerList);
                }
            } else {
                llout_region.setVisibility(View.GONE);
                llout_am.setVisibility(View.GONE);
                mAMList[0] = GlobalData.user.getData().getName();
                mAMId[0] = GlobalData.user.getData().getEmailid();

                dealerSpinner.setItems(nameList);
                dseSpinner.setItems(nameList);
                NAMES = new ArrayList<>();
                adapter.notifyDataSetChanged();
                ArrayList<String> amList = new ArrayList<>();
                amList.add(mAMId[0]);
                getDealerDetails(amList);
            }
        } else {
            mRegionList[0] = GlobalData.user.getData().getName();
            mRegionId[0] = GlobalData.user.getData().getEmailid();
            llout_region.setVisibility(View.GONE);

            areaSpinner.setItems(nameList);
            dealerSpinner.setItems(nameList);
            dseSpinner.setItems(nameList);

            ArrayList<String> rmList = new ArrayList<>();
            rmList.add(mRegionId[0]);
            getAMDetails(rmList);
        }

        getTrainingTitle();
        schedule.setOnClickListener(v ->
                createSchedule());
    }

    private void createSchedule() {
        if (title.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "Please select title", Toast.LENGTH_SHORT).show();
            return;
        }

        if (description.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "Please enter description", Toast.LENGTH_SHORT).show();
            return;
        }

        if (NAMES.size() == 0 || NAMES.get(0) == 0) {
            Toast.makeText(this, "Please select participant", Toast.LENGTH_SHORT).show();
            return;
        }

        if (fromTime.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "Please select from time", Toast.LENGTH_SHORT).show();
            return;
        }

        if (toTime.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "Please select to time", Toast.LENGTH_SHORT).show();
            return;
        }

        ArrayList<Integer> dseList = new ArrayList<>();
        for (int i = 0; i < NAMES.size(); i++) {
            dseList.add(Integer.valueOf(mDSEId[NAMES.get(i)]));
        }

        String channel = "_" + dateSelection.getText().toString().trim() + "_"
                + fromTime.getText().toString().trim();
        channel = channel.replace("-", "");
        channel = channel.replace(":", "");
        channel = GlobalData.user.getData().getEmp_code().trim() + channel;

        Gson gson = new Gson();
        JsonElement jsonElement = gson.toJsonTree(
                dseList, new TypeToken<ArrayList<String>>() {
                }.getType());

        String fTime = dateSelection.getText().toString().trim() + " " + fromTime.getText().toString().trim() + ":00";
        String tTime = dateSelection.getText().toString().trim() + " " + toTime.getText().toString().trim() + ":00";

        HashMap<String, String> map = new HashMap<>();
        map.put("dse", jsonElement.toString());
        map.put("title", title.getText().toString().trim());
        map.put("description", description.getText().toString().trim());
        map.put("fromdate", fTime);
        map.put("todate", tTime);
        map.put("channel", channel);

        if (new UtilService().isNetworkAvailable(ScheduleActivity.this)) {

            progressDialog = new TransparentProgressDialog(ScheduleActivity.this);
            progressDialog.show();

            restService.postSchedule(map).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }

                    if (response.body() != null && response.body().getStatus() == 200) {
                        GlobalData.showToast(ScheduleActivity.this, "Training scheduled successfully", Toast.LENGTH_SHORT).show();
                        finish();
                        overridePendingTransition(R.anim.animation_f_enter, R.anim.animation_f_leave);
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                        overridePendingTransition(R.anim.animation_f_enter, R.anim.animation_f_leave);
                    } else if (response.body() != null) {
                        GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                            overridePendingTransition(R.anim.animation_f_enter,
                                    R.anim.animation_f_leave);
                        }
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            dateSelection.setText(sdf.format(myCalendar.getTime()));
            fromTime.setText("");
            toTime.setText("");
        }
    };

    public static Timepoint[] generateTimepoints(int minutesInterval) {
        List<Timepoint> timepoints = new ArrayList<>();

        for (int minute = 0; minute <= 1440; minute += minutesInterval) {
            int currentHour = minute / 60;
            int currentMinute = minute - (currentHour > 0 ? (currentHour * 60) : 0);
            if (currentHour == 24)
                continue;
            timepoints.add(new Timepoint(currentHour, currentMinute));
        }
        return timepoints.toArray(new Timepoint[timepoints.size()]);
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    private void getDSEDetails(ArrayList<String> dealerList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ScheduleActivity.this))) {
            progressDialog = new TransparentProgressDialog(ScheduleActivity.this);
            progressDialog.show();
            try {
                Gson gson = new Gson();
                JsonElement jsonElement = gson.toJsonTree(
                        dealerList, new TypeToken<ArrayList<String>>() {
                        }.getType());

                HashMap<String, String> map = new HashMap<>();
                map.put("dealer_code", jsonElement.toString());
                map.put("typeid", "");

                restService.getDseList(map).enqueue(new Callback<DSEResponse>() {
                    @Override
                    public void onResponse(Call<DSEResponse> call, Response<DSEResponse> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null && response.body().getStatus() == 200) {
                            DSE_LIST = response.body().getData();
                            if (DSE_LIST != null && DSE_LIST.size() > 0) {
                                mDSEList = new String[DSE_LIST.size() + 1];
                                mDSEList[0] = "Select";
                                mDSEId = new String[DSE_LIST.size() + 1];
                                mDSEId[0] = "-1";
                                StringBuilder SMPIN = new StringBuilder();
                                for (int i = 1; i <= DSE_LIST.size(); i++) {
                                    mDSEList[i] = DSE_LIST.get(i - 1).getName();
                                    mDSEId[i] = DSE_LIST.get(i - 1).getUserid();
                                    SMPIN.append((SMPIN.length() == 0) ? DSE_LIST.get(i - 1).getSmpin() : "," + DSE_LIST.get(i - 1).getSmpin());
                                }

                                dseSpinner.setItems(mDSEList);
                                dseSpinner.hasNoneOption(true);
                                dseSpinner.setSelection(new int[]{0});
                                NAMES = new ArrayList<>();
                                dseSpinner.setSelection(0);
                            } else {
                                mDSEList = new String[1];
                                mDSEList[0] = "Select";
                                mDSEId = new String[1];
                                mDSEId[0] = "-1";
                                dseSpinner.setItems(mDSEList);
                                dseSpinner.hasNoneOption(true);
                                dseSpinner.setSelection(new int[]{0});
                                NAMES = new ArrayList<>();
                                dseSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(ScheduleActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(ScheduleActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<DSEResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(ScheduleActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(ScheduleActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void getRMDetails() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ScheduleActivity.this))) {
            progressDialog = new TransparentProgressDialog(ScheduleActivity.this);
            progressDialog.show();
            try {
                restService.getRMList().enqueue(new Callback<RMResponse>() {
                    @Override
                    public void onResponse(Call<RMResponse> call, Response<RMResponse> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                mRegionList = new String[response.body().getData().size() + 1];
                                mRegionList[0] = "Select";
                                mRegionId = new String[response.body().getData().size() + 1];
                                mRegionId[0] = "-1";
                                for (int i = 1; i <= response.body().getData().size(); i++) {
                                    mRegionList[i] = response.body().getData().get(i - 1).getRm_name();
                                    mRegionId[i] = response.body().getData().get(i - 1).getRm_email();
                                }

                                regionSpinner.setItems(mRegionList);
                                regionSpinner.hasNoneOption(true);
                                regionSpinner.setSelection(new int[]{0});
                                regionSpinner.setSelection(0);
                            } else {
                                mRegionList = new String[1];
                                mRegionList[0] = "Select";
                                mRegionId = new String[1];
                                mRegionId[0] = "-1";
                                regionSpinner.setItems(mRegionList);
                                regionSpinner.hasNoneOption(true);
                                regionSpinner.setSelection(new int[]{0});
                                regionSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(ScheduleActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(ScheduleActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<RMResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(ScheduleActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(ScheduleActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void getTrainingTitle() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ScheduleActivity.this))) {
            try {
                restService.getTrainingTitle().enqueue(new Callback<TitleResponse>() {
                    @Override
                    public void onResponse(Call<TitleResponse> call, Response<TitleResponse> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                TITLES = response.body().getData();
                                items = new String[TITLES.size()];
                                for (int i = 0; i < response.body().getData().size(); i++) {
                                    items[i] = TITLES.get(i).getTitle();
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<TitleResponse> call, Throwable t) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void getAMDetails(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ScheduleActivity.this))) {
            progressDialog = new TransparentProgressDialog(ScheduleActivity.this);
            progressDialog.show();
            try {
                Gson gson = new Gson();
                JsonElement jsonElement = gson.toJsonTree(
                        rmList, new TypeToken<ArrayList<String>>() {
                        }.getType());

                HashMap<String, String> map = new HashMap<>();
                map.put("rm_email", jsonElement.toString());

                restService.getAMList(map).enqueue(new Callback<AMResponse>() {
                    @Override
                    public void onResponse(Call<AMResponse> call, Response<AMResponse> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                mAMList = new String[response.body().getData().size() + 1];
                                mAMList[0] = "Select";
                                mAMId = new String[response.body().getData().size() + 1];
                                mAMId[0] = "-1";
                                for (int i = 1; i <= response.body().getData().size(); i++) {
                                    mAMList[i] = response.body().getData().get(i - 1).getAm_name();
                                    mAMId[i] = response.body().getData().get(i - 1).getAm_email();
                                }

                                areaSpinner.setItems(mAMList);
                                areaSpinner.hasNoneOption(true);
                                areaSpinner.setSelection(new int[]{0});
                                areaSpinner.setSelection(0);
                            } else {
                                mAMList = new String[1];
                                mAMList[0] = "Select";
                                mAMId = new String[1];
                                mAMId[0] = "-1";
                                areaSpinner.setItems(mAMList);
                                areaSpinner.hasNoneOption(true);
                                areaSpinner.setSelection(new int[]{0});
                                areaSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(ScheduleActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(ScheduleActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<AMResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(ScheduleActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(ScheduleActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void getDealerDetails(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ScheduleActivity.this))) {
            progressDialog = new TransparentProgressDialog(ScheduleActivity.this);
            progressDialog.show();
            try {
                Gson gson = new Gson();
                JsonElement jsonElement = gson.toJsonTree(
                        rmList, new TypeToken<ArrayList<String>>() {
                        }.getType());

                HashMap<String, String> map = new HashMap<>();
                map.put("am_email", jsonElement.toString());

                restService.getDealerList(map).enqueue(new Callback<DealerResponse>() {
                    @Override
                    public void onResponse(Call<DealerResponse> call, Response<DealerResponse> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                mDealerList = new String[response.body().getData().size() + 1];
                                mDealerList[0] = "Select";
                                mDealerId = new String[response.body().getData().size() + 1];
                                mDealerId[0] = "-1";
                                for (int i = 1; i <= response.body().getData().size(); i++) {
                                    mDealerList[i] = response.body().getData().get(i - 1).getDealer_name();
                                    mDealerId[i] = response.body().getData().get(i - 1).getDealer_code();
                                }

                                dealerSpinner.setItems(mDealerList);
                                dealerSpinner.hasNoneOption(true);
                                dealerSpinner.setSelection(new int[]{0});
                                dealerSpinner.setSelection(0);
                            } else {
                                mDealerList = new String[1];
                                mDealerList[0] = "Select";
                                mDealerId = new String[1];
                                mDealerId[0] = "-1";
                                dealerSpinner.setItems(mDealerList);
                                dealerSpinner.hasNoneOption(true);
                                dealerSpinner.setSelection(new int[]{0});
                                dealerSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(ScheduleActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(ScheduleActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<DealerResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(ScheduleActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(ScheduleActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    class PartiPantAdapter extends BaseAdapter {

        PartiPantAdapter() {

        }

        @Override
        public int getCount() {
            return NAMES.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.participant_item, null);
                holder.name = convertView.findViewById(R.id.name);
                holder.remove = convertView.findViewById(R.id.remove);
                holder.smpin = convertView.findViewById(R.id.smpin);
                holder.userIcon = convertView.findViewById(R.id.userIcon);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.name.setText(DSE_LIST.get(NAMES.get(position) - 1).getFullName());
            holder.smpin.setText(String.format("SMPIN : %s", DSE_LIST.get(NAMES.get(position) - 1).getSmpin()));
            holder.remove.setTag(position);

            Glide.with(ScheduleActivity.this).load(DSE_LIST.get(NAMES.get(position) - 1).getProfile())
                    .thumbnail(Glide.with(ScheduleActivity.this).load(R.drawable.gif_loader))
                    .into(holder.userIcon);

            holder.remove.setOnClickListener(view -> {
                int pos = (int) view.getTag();
                new androidx.appcompat.app.AlertDialog.Builder(ScheduleActivity.this)
                        .setTitle(DSE_LIST.get(NAMES.get(pos) - 1).getName())
                        .setMessage("Are you sure to remove?")
                        .setPositiveButton("Yes",
                                (dialog, which) -> {
                                    NAMES.remove(pos);
                                    notifyDataSetChanged();
                                }).setNegativeButton("No", null).show();
            });
            return convertView;
        }

        class ViewHolder {
            TextView name, smpin;
            ImageButton remove;
            CircularImageView userIcon;
        }
    }
}