package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
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.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.ExpandableHeightGridView;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MultiSelectSpinner;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AMResponse;
import com.cygnusa.hyperm.wrappers.Area;
import com.cygnusa.hyperm.wrappers.CTAssessment;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.DSE;
import com.cygnusa.hyperm.wrappers.DSEResponse;
import com.cygnusa.hyperm.wrappers.Dealer;
import com.cygnusa.hyperm.wrappers.DealerResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetCancelOrRescheduleList;
import com.cygnusa.hyperm.wrappers.GetLevelDataList;
import com.cygnusa.hyperm.wrappers.ParticipantList;
import com.cygnusa.hyperm.wrappers.RMResponse;
import com.cygnusa.hyperm.wrappers.Reasons;
import com.cygnusa.hyperm.wrappers.Region;
import com.cygnusa.hyperm.wrappers.TrainingTitleLevel;
import com.cygnusa.hyperm.wrappers.VenueAreaList;
import com.cygnusa.hyperm.wrappers.VenueAreaLocation;
import com.cygnusa.hyperm.wrappers.ZoneListResponse;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.wdullaer.materialdatetimepicker.time.Timepoint;

import net.danlew.android.joda.JodaTimeAndroid;

import org.jetbrains.annotations.NotNull;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.json.JSONArray;
import org.json.JSONException;

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 ModifyClassRoomActivity extends AppCompatActivity {

    ImageButton levelSpinner;
    DSE dse = new DSE();
    String strStartDate = "", strEndDate = "";
    List<ParticipantList> mParticipant = new ArrayList<>();
    ArrayList<Region> RM_BF = new ArrayList<>();
    ArrayList<Area> AM_BF = new ArrayList<>();
    ArrayList<Dealer> DEALER_BF = new ArrayList<>();
    ArrayList<DSE> DSE_BF = new ArrayList<>();
    ExpandableHeightGridView gridView;
    JSONArray arrayFromTime, arrayToTime;
    private ApiService restService;
    private TransparentProgressDialog progressDialog;
    private Switch adHocSwitch;
    private RadioButton rbScooter, rbMotor, rbBoth, radioReschdule, radioCancel, radioModify;
    private TextView trainingTitle, startDate, endDate, venueView, totalTime;
    private EditText description, venueAddress, preAssessmentCount, preAssessmentDuration,
            postAssessmentCount, postAssessmentDuration, otherTitle, preAssesmentName, postAssesmentName, otherReschedule;
    private MultiSelectSpinner regionSpinner, areaSpinner, dealerSpinner, dseSpinner;
    private LinearLayout timeView, venueDealerLayout, postAssesmentLayout, preAssessmentLayout, otherLayout;
    private Spinner venueAreaSpinner, venueDealerSpinner, zoneSpinner;
    private CheckBox cbPreAssessment, cbPostAssessment, cbFeedback;
    private Button btnAddParticipant;
    private LinearLayout lloutAddParticipant, lloutStartDate, lloutDealer, lloutPostAssessment, lloutPreAssessment;
    private RelativeLayout rloutReschedule, rloutCancel;
    private ImageView imgReschedule, imgCancel;
    private TextView txtReasonReschdule, txtReasonCancel;
    private String[] TRAINING_TITLES, RM_NAMES, AM_NAMES, DEALER_NAMES, DSE_NAMES;
    private String[] RM_IDS, AM_IDS, DEALER_IDS, DSE_IDS;
    private String[] VENUE_SELECTION = {"Dealer", "Other"};
    private String trainingTitleId = "", venueDelaerCode = "", venueAreaCode, venueType = "";
    private List<GetLevelDataList> TITLES = new ArrayList<>();
    private int TRAINING_POSITION = -1;
    private String[] emptyList = {"Select"};
    private ArrayList<DSE> DSE_LIST = new ArrayList<>();
    private List<VenueAreaList> VENUE_AREA = new ArrayList<>();
    private List<Dealer> VENUE_DEALER = new ArrayList<>();
    private ArrayList<DSE> PARTICIPANTS = new ArrayList<>();
    private PartiPantAdapter adapter;
    private Calendar myCalendar = Calendar.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat setFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
    private boolean isStartDate;
    private AlertDialog dialog;
    private EditText reason;
    private String dateDifferReason;
    TextView txtFromTime;
    TextView txtToTime;
    private TextView noOfDays;
    String amEmail = "", dealerCode = "";
    String segment = "1";
    private long totalMinitues = 0, totalHours = 0;

    private String hours = "", minutes = "";

    private long editTotalMinitues = 0, editTtotalHours = 0;

    private String editHours = "", editMinutes = "";
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            timeView.removeAllViews();
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            if (isStartDate) {
                startDate.setText(setFormat.format(myCalendar.getTime()));
                strStartDate = sdf.format(myCalendar.getTime());
                endDate.setText("");
                totalTime.setText("");
                totalMinitues = 0;
                totalHours = 0;
            } else {
                strEndDate = sdf.format(myCalendar.getTime());
                totalTime.setText("");
                totalMinitues = 0;
                totalHours = 0;
                if (strStartDate == null || strStartDate.equalsIgnoreCase("")) {
                    GlobalData.toast(ModifyClassRoomActivity.this, "Need to select start date first");
                    endDate.setText("");
                    return;
                }
                endDate.setText(setFormat.format(myCalendar.getTime()));
                LocalDate start = LocalDate.parse(strStartDate);
                LocalDate end = LocalDate.parse(strEndDate);
                long num = Days.daysBetween(start, end).getDays() + 1;
                String msg = "";
                if (Integer.parseInt(GlobalData.scheduledDataList.get(0).getTrainingDays()) > num) {
                    msg = "The " + TITLES.get(TRAINING_POSITION - 1).getLvlName()
                            + " Training title duration must be " + GlobalData.scheduledDataList.get(0).getTrainingDays()
                            + " Days. Do you wants to reduce the duration of Training? If yes!";
                } else if (Integer.parseInt(GlobalData.scheduledDataList.get(0).getTrainingDays()) < num) {
                    msg = "The " + TITLES.get(TRAINING_POSITION - 1).getLvlName()
                            + " Training title duration must be " + GlobalData.scheduledDataList.get(0).getTrainingDays()
                            + " Days. Do you wants to increase the duration of Training? If yes!";
                }
                if (msg.isEmpty()) {
                    arrayFromTime = null;
                    arrayToTime = null;
                    showTimeFrame(Integer.parseInt(GlobalData.scheduledDataList.get(0).getTrainingDays()));
                } else {
                    View mView = LayoutInflater.from(ModifyClassRoomActivity.this).inflate(R.layout.date_alert, null, false);
                    TextView mTitle = mView.findViewById(R.id.mTitle);
                    reason = mView.findViewById(R.id.reason);
                    mTitle.setText(msg);

                    mView.findViewById(R.id.actionCancel).setOnClickListener(view12 -> {
                        endDate.setText("");
                        dialog.dismiss();
                    });

                    mView.findViewById(R.id.actionSubmit).setOnClickListener(view1 -> {
                        dateDifferReason = reason.getText().toString().trim();
                        if (dateDifferReason.isEmpty()) {
                            Toast.makeText(ModifyClassRoomActivity.this, "Please enter reason", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        arrayFromTime = null;
                        arrayToTime = null;
                        showTimeFrame(Math.toIntExact(num));
                        dialog.dismiss();
                    });

                    AlertDialog.Builder builder = new AlertDialog.Builder(ModifyClassRoomActivity.this);
                    builder.setView(mView);
                    dialog = builder.create();
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                }
            }
        }
    };
    private List<Reasons> REASONS = new ArrayList<>();
    private String[] reasonName = {"None"};
    private String[] reasonId = {"None"};
    private String reasonIdString = "", modifyType = "";
    private RadioGroup radio_group;
    private RelativeLayout trainingTitleView, venueLayout;

    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()]);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JodaTimeAndroid.init(this);
        setContentView(R.layout.activity_modify_classroom_new);

        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);

        adHocSwitch = findViewById(R.id.adHocSwitch);

        rbScooter = findViewById(R.id.rbScooter);
        rbMotor = findViewById(R.id.rbMotor);
        rbBoth = findViewById(R.id.rbBoth);
        otherTitle = findViewById(R.id.otherTitle);
        otherLayout = findViewById(R.id.otherLayout);

        trainingTitle = findViewById(R.id.trainingTitle);
        startDate = findViewById(R.id.startDate);
        endDate = findViewById(R.id.endDate);
        venueView = findViewById(R.id.venueView);
        levelSpinner = findViewById(R.id.levelSpinner);
        description = findViewById(R.id.description);
        venueAddress = findViewById(R.id.venueAddress);
        preAssessmentCount = findViewById(R.id.preAssessmentCount);
        preAssessmentDuration = findViewById(R.id.preAssessmentDuration);
        postAssessmentCount = findViewById(R.id.postAssessmentCount);
        postAssessmentDuration = findViewById(R.id.postAssessmentDuration);
        radioReschdule = findViewById(R.id.radioReschdule);
        radioCancel = findViewById(R.id.radioCancel);
        imgReschedule = findViewById(R.id.imgReschedule);
        imgCancel = findViewById(R.id.imgCancel);
        otherReschedule = findViewById(R.id.otherReschedule);
        otherReschedule.setVisibility(View.GONE);
        txtReasonReschdule = findViewById(R.id.txtReasonReschdule);
        txtReasonCancel = findViewById(R.id.txtReasonCancel);
        totalTime = findViewById(R.id.totalTime);
        totalTime.setVisibility(View.VISIBLE);

        radio_group = findViewById(R.id.radio_group);
        trainingTitleView = findViewById(R.id.trainingTitleView);
        lloutStartDate = findViewById(R.id.lloutStartDate);
        venueLayout = findViewById(R.id.venueLayout);
        lloutDealer = findViewById(R.id.lloutDealer);
        lloutPostAssessment = findViewById(R.id.lloutPostAssessment);
        lloutPreAssessment = findViewById(R.id.lloutPreAssessment);

        zoneSpinner = findViewById(R.id.zoneSpinner);
        regionSpinner = findViewById(R.id.regionSpinner);
        areaSpinner = findViewById(R.id.areaSpinner);
        dealerSpinner = findViewById(R.id.dealerSpinner);
        dseSpinner = findViewById(R.id.dseSpinner);

        noOfDays = findViewById(R.id.noOfDays);

        gridView = findViewById(R.id.participantList);
        adapter = new PartiPantAdapter();
        gridView.setAdapter(adapter);
        timeView = findViewById(R.id.timeView);
        venueDealerLayout = findViewById(R.id.venueDealerLayout);
        postAssesmentLayout = findViewById(R.id.postAssesmentLayout);
        preAssessmentLayout = findViewById(R.id.preAssessmentLayout);

        venueAreaSpinner = findViewById(R.id.venueAreaSpinner);
        venueDealerSpinner = findViewById(R.id.venueDealerSpinner);
        preAssesmentName = findViewById(R.id.preAssesmentName);
        postAssesmentName = findViewById(R.id.postAssesmentName);

        cbPreAssessment = findViewById(R.id.cbPreAssessment);
        cbPostAssessment = findViewById(R.id.cbPostAssessment);
        cbFeedback = findViewById(R.id.cbFeedback);


        btnAddParticipant = findViewById(R.id.btnAddParticipant);
        lloutAddParticipant = findViewById(R.id.lloutAddParticipant);
        btnAddParticipant.setEnabled(false);

        radio_group.setEnabled(false);
        trainingTitleView.setEnabled(false);
        lloutStartDate.setEnabled(false);
        venueLayout.setEnabled(false);
        venueDealerLayout.setEnabled(false);
        lloutDealer.setEnabled(false);
        lloutPostAssessment.setEnabled(false);
        lloutPreAssessment.setEnabled(false);
        // venueAddress.setEnabled(false);
        cbPostAssessment.setEnabled(false);
        cbPreAssessment.setEnabled(false);
        preAssesmentName.setEnabled(false);
        preAssessmentCount.setEnabled(false);
        preAssessmentDuration.setEnabled(false);
        venueAreaSpinner.setEnabled(false);
        venueAreaSpinner.setClickable(false);

        postAssesmentName.setEnabled(false);
        postAssessmentCount.setEnabled(false);
        postAssessmentDuration.setEnabled(false);

        adHocSwitch.setEnabled(false);
        description.setEnabled(false);
        cbFeedback.setEnabled(false);
        rbScooter.setEnabled(false);
        rbBoth.setEnabled(false);
        rbMotor.setEnabled(false);

        startDate.setEnabled(false);
        startDate.setClickable(false);
        endDate.setEnabled(false);
        endDate.setClickable(false);

        rloutCancel = findViewById(R.id.rloutCancl);
        radioModify = findViewById(R.id.radioModify);
        rloutReschedule = findViewById(R.id.rloutReschedule);

        getVenueArea(GlobalData.user.getData().getZone());


        rbScooter.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                segment = "2";
            }
        });

        rbMotor.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                segment = "1";
            }
        });

        rbBoth.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                segment = "3";
            }
        });


        radioModify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rloutReschedule.setVisibility(View.GONE);
                    rloutCancel.setVisibility(View.GONE);
                    otherReschedule.setVisibility(View.GONE);
                    radioReschdule.setChecked(false);
                    radioCancel.setChecked(false);
                    radioModify.setChecked(true);
                    modifyType = "modify";

                    radio_group.setEnabled(false);
                    radio_group.setClickable(false);
                    trainingTitleView.setEnabled(false);
                    lloutStartDate.setEnabled(false);
                    venueLayout.setEnabled(true);
                    venueDealerLayout.setEnabled(true);
                    lloutDealer.setEnabled(true);
                    description.setEnabled(true);
                    lloutPostAssessment.setEnabled(true);
                    venueAreaSpinner.setEnabled(true);
                    venueAreaSpinner.setClickable(true);
                    venueDealerSpinner.setEnabled(true);
                    venueDealerSpinner.setClickable(true);
                    cbPreAssessment.setEnabled(true);
                    cbPreAssessment.setClickable(true);
                    cbPostAssessment.setEnabled(true);
                    cbPostAssessment.setClickable(true);

                    preAssesmentName.setEnabled(true);
                    preAssessmentCount.setEnabled(true);
                    preAssessmentDuration.setEnabled(true);

                    postAssesmentName.setEnabled(true);
                    postAssessmentCount.setEnabled(true);
                    postAssessmentDuration.setEnabled(true);
                    btnAddParticipant.setEnabled(true);
                    startDate.setEnabled(false);
                    endDate.setEnabled(false);
                    startDate.setClickable(false);
                    endDate.setEnabled(false);

                    if (txtFromTime != null) {
                        txtFromTime.setEnabled(true);
                        txtToTime.setEnabled(true);
                    }

                    gridView.setEnabled(true);
                    lloutPreAssessment.setEnabled(true);
                    // venueAddress.setEnabled(true);
                    adHocSwitch.setEnabled(false);
                    description.setEnabled(true);
                    cbFeedback.setEnabled(true);
                    cbFeedback.setClickable(true);

                    getVenueArea(GlobalData.user.getData().getZone());
                }
            }
        });


        rloutReschedule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setRescheduleSelection();
            }
        });

        rloutCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setCancelSelection();
            }
        });


        rloutReschedule.setVisibility(View.GONE);
        rloutCancel.setVisibility(View.GONE);

        radioCancel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rloutReschedule.setVisibility(View.GONE);
                    rloutCancel.setVisibility(View.VISIBLE);
                    otherReschedule.setVisibility(View.GONE);
                    radioReschdule.setChecked(false);
                    radioModify.setChecked(false);
                    radioCancel.setChecked(true);
                    modifyType = "cancel";


                    radio_group.setEnabled(false);
                    radio_group.setClickable(false);
                    trainingTitleView.setEnabled(false);
                    lloutStartDate.setEnabled(true);
                    venueLayout.setEnabled(false);
                    description.setEnabled(false);
                    venueDealerLayout.setEnabled(false);
                    lloutDealer.setEnabled(false);
                    lloutPostAssessment.setEnabled(false);
                    venueAreaSpinner.setEnabled(false);
                    venueAreaSpinner.setClickable(false);
                    venueDealerSpinner.setEnabled(false);
                    venueDealerSpinner.setClickable(false);
                    cbPreAssessment.setEnabled(false);
                    cbPreAssessment.setClickable(false);
                    cbPostAssessment.setEnabled(false);
                    cbPostAssessment.setClickable(false);
                    btnAddParticipant.setEnabled(false);
                    preAssesmentName.setEnabled(false);
                    preAssessmentCount.setEnabled(false);
                    preAssessmentDuration.setEnabled(false);

                    postAssesmentName.setEnabled(false);
                    postAssessmentCount.setEnabled(false);
                    postAssessmentDuration.setEnabled(false);

                    startDate.setEnabled(false);
                    endDate.setEnabled(false);
                    startDate.setEnabled(false);
                    endDate.setEnabled(false);
                    gridView.setEnabled(false);

                    if (txtFromTime != null) {
                        txtFromTime.setEnabled(false);
                        txtToTime.setEnabled(false);
                    }

                    lloutPreAssessment.setEnabled(false);
                    // venueAddress.setEnabled(false);
                    adHocSwitch.setEnabled(false);
                    description.setEnabled(false);
                    cbFeedback.setEnabled(false);
                    cbFeedback.setClickable(false);

                    getVenueArea(GlobalData.user.getData().getZone());
                }
            }
        });

        radioReschdule.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rloutReschedule.setVisibility(View.VISIBLE);
                    rloutCancel.setVisibility(View.GONE);
                    otherReschedule.setVisibility(View.GONE);
                    radioCancel.setChecked(false);
                    radioModify.setChecked(false);
                    radioReschdule.setChecked(true);
                    modifyType = "Reschedule";


                    radio_group.setEnabled(false);
                    radio_group.setClickable(false);
                    trainingTitleView.setEnabled(false);
                    lloutStartDate.setEnabled(true);
                    venueLayout.setEnabled(false);
                    venueDealerLayout.setEnabled(false);
                    lloutDealer.setEnabled(false);
                    description.setEnabled(false);
                    lloutPostAssessment.setEnabled(false);
                    venueAreaSpinner.setEnabled(false);
                    venueAreaSpinner.setClickable(false);
                    venueDealerSpinner.setEnabled(false);
                    venueDealerSpinner.setClickable(false);
                    cbPreAssessment.setEnabled(false);
                    cbPreAssessment.setClickable(false);
                    cbPostAssessment.setEnabled(false);
                    cbPostAssessment.setClickable(false);

                    preAssesmentName.setEnabled(false);
                    preAssessmentCount.setEnabled(false);
                    preAssessmentDuration.setEnabled(false);

                    postAssesmentName.setEnabled(false);
                    postAssessmentCount.setEnabled(false);
                    postAssessmentDuration.setEnabled(false);
                    btnAddParticipant.setEnabled(false);

                    startDate.setEnabled(true);
                    startDate.setClickable(true);
                    endDate.setClickable(true);
                    endDate.setEnabled(true);

                    if (txtFromTime != null) {
                        txtFromTime.setEnabled(true);
                        txtToTime.setEnabled(true);
                    }

                    gridView.setEnabled(false);
                    lloutPreAssessment.setEnabled(false);
                    //   venueAddress.setEnabled(false);
                    adHocSwitch.setEnabled(false);
                    description.setEnabled(false);
                    cbFeedback.setEnabled(false);
                    cbFeedback.setClickable(false);

                    getVenueArea(GlobalData.user.getData().getZone());
                }
            }
        });


        btnAddParticipant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lloutAddParticipant.setVisibility(View.VISIBLE);
                btnAddParticipant.setVisibility(View.GONE);
            }
        });

        cbPreAssessment.setOnCheckedChangeListener((compoundButton, b) -> preAssessmentLayout.setVisibility(b ? View.VISIBLE : View.GONE));

        cbPostAssessment.setOnCheckedChangeListener((compoundButton, b) -> postAssesmentLayout.setVisibility(b ? View.VISIBLE : View.GONE));

        cbPreAssessment.setChecked(true);
        cbPostAssessment.setChecked(false);
        cbFeedback.setChecked(false);
        otherLayout.setVisibility(View.GONE);

        restService = ((MainApplication) getApplication()).getClient();

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

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

        venueAreaSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                ArrayList<String> area = new ArrayList<>();
                if (pos == 0) {
                    area.add("Select Dealer");
                    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(ModifyClassRoomActivity.this,
                            R.layout.class_text_ms, area);
                    spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_new);
                    venueDealerSpinner.setAdapter(spinnerArrayAdapter);
                } else {
                    area.add(VENUE_AREA.get(pos - 1).getAmEmail());
                    amEmail = VENUE_AREA.get(pos - 1).getAmEmail();
                    getVenueDealer(area);
                }
            }

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

            }
        });

        venueDealerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos == 0) {
                    venueAddress.setText("");
                } else {
                    dealerCode = VENUE_DEALER.get(pos - 1).getDealer_code();
                    venueAddress.setText(VENUE_DEALER.get(pos - 1).getAddress());
                    //   venueAddress.setEnabled(false);
                }
            }

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

            }
        });

        zoneSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                RM_BF = new ArrayList<>();
                AM_BF = new ArrayList<>();
                DEALER_BF = new ArrayList<>();
                DSE_BF = new ArrayList<>();

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

                regionSpinner.setSelection(0);
                areaSpinner.setSelection(0);
                dealerSpinner.setSelection(0);
                dseSpinner.setSelection(0);
                PARTICIPANTS = new ArrayList<>();
                adapter.notifyDataSetChanged();

                if (position != 0) {
                    getRMDetails(zoneSpinner.getSelectedItem().toString());
                }
                getVenueArea(zoneSpinner.getSelectedItem().toString());
            }

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

            }
        });

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

                    areaSpinner.setSelection(0);
                    dealerSpinner.setSelection(0);
                    regionSpinner.setSelection(0);
                    dseSpinner.setSelection(0);
                    PARTICIPANTS = new ArrayList<>();
                    adapter.notifyDataSetChanged();
                }
            }

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

            }
        });

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

                    areaSpinner.setSelection(0);
                    dealerSpinner.setSelection(0);
                    dseSpinner.setSelection(0);
                    PARTICIPANTS = new ArrayList<>();
                    adapter.notifyDataSetChanged();
                }
            }

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

            }
        });

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

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

            }
        });

        dseSpinner.setListener(new MultiSelectSpinner.OnMultipleItemsSelectedListener() {
            @Override
            public void selectedIndices(List<Integer> indices) {
                if (PARTICIPANTS == null || PARTICIPANTS.size() == 0) {
                    PARTICIPANTS = new ArrayList<>();
                } else {
                    for (DSE sDse : DSE_LIST) {
                        if (PARTICIPANTS.size() == 0) {
                            break;
                        } else {
                            for (DSE tDse : PARTICIPANTS) {
                                if (sDse.getSmpin().equalsIgnoreCase(tDse.getSmpin())) {
                                    PARTICIPANTS.remove(tDse);
                                    break;
                                }
                            }
                        }
                    }
                }

                if (indices.size() != 0 && indices.get(0) != 0) {
                    for (int i = 0; i < indices.size(); i++) {
                        PARTICIPANTS.add(DSE_LIST.get(indices.get(i) - 1));
                    }
                }
                adapter.notifyDataSetChanged();
            }

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

            }
        });

        findViewById(R.id.trainingTitleView).setOnClickListener(view -> {
            int selection = 0;
            if (!trainingTitle.getText().toString().isEmpty()) {
                selection = Arrays.asList(TRAINING_TITLES).indexOf(trainingTitle.getText().toString().trim());
            }
            new AlertDialog.Builder(ModifyClassRoomActivity.this).setTitle("Select Training")
                    .setSingleChoiceItems(TRAINING_TITLES, selection, null)
                    .setNegativeButton("Cancel", null)
                    .setPositiveButton("Ok", (dialog, whichButton) -> {
                        dialog.dismiss();
                        int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                        trainingTitle.setText(TRAINING_TITLES[selectedPosition]);


                        if (TRAINING_TITLES[selectedPosition].toLowerCase().contains("other")) {
                            otherLayout.setVisibility(View.VISIBLE);
                        } else {
                            otherLayout.setVisibility(View.GONE);
                        }
                        TRAINING_POSITION = selectedPosition;
                    })
                    .show();
        });

        findViewById(R.id.popupView).setOnClickListener(view -> {
            if (!rbScooter.isChecked() && !rbMotor.isChecked() && !rbBoth.isChecked()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select business segment", Toast.LENGTH_SHORT).show();
                return;
            }
            if (DSE_BF == null || DSE_BF.size() == 0) {
                getRMBF(zoneSpinner.getSelectedItem().toString());
            } else {
                showPopup();
            }
        });

        venueView.setText(VENUE_SELECTION[0]);
        venueDealerLayout.setVisibility(View.VISIBLE);

        findViewById(R.id.venueLayout).setOnClickListener(view -> {
            int selection = 0;
            if (!venueView.getText().toString().isEmpty()) {
                selection = Arrays.asList(VENUE_SELECTION).indexOf(venueView.getText().toString().trim());
            }
            new AlertDialog.Builder(ModifyClassRoomActivity.this).setTitle("Select Venue Type")
                    .setSingleChoiceItems(VENUE_SELECTION, selection, null)
                    .setNegativeButton("Cancel", null)
                    .setPositiveButton("Ok", (dialog, whichButton) -> {
                        dialog.dismiss();
                        int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                        venueView.setText(VENUE_SELECTION[selectedPosition]);
                        getVenueArea(zoneSpinner.getSelectedItem().toString());
                        if (selectedPosition == 0) {
                            venueDealerLayout.setVisibility(View.VISIBLE);
                        } else {
                            venueDealerLayout.setVisibility(View.GONE);
                            //      venueAddress.setEnabled(true);
                        }
                    })
                    .show();
        });

        findViewById(R.id.actionSubmit).setOnClickListener(view -> {
            if (validate()) {
                if (modifyType.equalsIgnoreCase("cancel")) {
                    sendCancelReasonDataToServer();
                } else if (modifyType.equalsIgnoreCase("Reschedule")) {
                    sendModifyReasonDataToServer();
                } else {
                    publishTraining();
                }
            }
        });

        findViewById(R.id.actionCancel).setOnClickListener(view -> {
            onBackPressed();
        });

        startDate.setOnClickListener(v -> {
            if (TRAINING_POSITION == -1) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select Training", Toast.LENGTH_SHORT).show();
                return;
            }
            isStartDate = true;
            DatePickerDialog dialog = new DatePickerDialog(ModifyClassRoomActivity.this, dateSetListener, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH));
            dialog.getDatePicker().setMinDate(new Date().getTime());
            dialog.show();
        });

        endDate.setOnClickListener(v -> {
            if (startDate.getText().toString().trim().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select start date.", Toast.LENGTH_SHORT).show();
                return;
            }
            isStartDate = false;
            DatePickerDialog dialog = new DatePickerDialog(ModifyClassRoomActivity.this, dateSetListener, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH));
            try {
                dialog.getDatePicker().setMinDate(Objects.requireNonNull(setFormat.parse(startDate.getText().toString().trim())).getTime());
            } catch (Exception e) {
                e.printStackTrace();
            }
            dialog.show();
        });

        trainingTitle.post(() -> {
            getTrainingTitle();
            getZoneDetails();

        });


        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setAllModifyData();
            }
        }, 1000);

        getReasons();

    }

    private void sendModifyReasonDataToServer() {

        HashMap<String, String> map = new HashMap<>();
        map.put("startdate", strStartDate);
        map.put("enddate", strEndDate);
        ArrayList<String> starttime = new ArrayList<>();
        ArrayList<String> endtime = new ArrayList<>();
        for (int i = 0; i < timeView.getChildCount(); i++) {
            View view = timeView.getChildAt(i);
            TextView txtFromTime = view.findViewById(R.id.txtFromTime);
            TextView txtToTime = view.findViewById(R.id.txtToTime);
            starttime.add(txtFromTime.getText().toString().trim());
            endtime.add(txtToTime.getText().toString().trim());
        }

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

        map.put("starttime", jsonElement.toString());
        map.put("endtime", jsonElement1.toString());
        map.put("training_total_hours", totalTime.getText().toString());
        restService.sendRescheduleReasonToServer(GlobalData.scheduledDataList.get(0).getScheduleId(), reasonIdString, map).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {

                if (response.body() != null) {
                    if (response.body().getResponse().equalsIgnoreCase("Success")) {
                        GlobalData.toast(ModifyClassRoomActivity.this, "Rescheduled Successfully");
                        startActivity(new Intent(ModifyClassRoomActivity.this, ClassRoomTrainerTainingActivity.class));
                        finish();
                    } else {
                        GlobalData.toast(ModifyClassRoomActivity.this, response.body().getResponseText());
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    finish();
                } 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();
                    }
                }
            }

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

            }
        });
    }

    private void sendCancelReasonDataToServer() {
        restService.sendReasonToServer(GlobalData.scheduledDataList.get(0).getScheduleId(), reasonIdString).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    if (response.body().getResponse().equalsIgnoreCase("Success")) {
                        GlobalData.toast(ModifyClassRoomActivity.this, "Cancelled Successfully");
                        startActivity(new Intent(ModifyClassRoomActivity.this, ClassRoomTrainerTainingActivity.class));
                        finish();
                    } else {
                        GlobalData.toast(ModifyClassRoomActivity.this, response.body().getResponseText());
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    finish();
                } 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();
                    }
                }
            }

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

            }
        });
    }

    private void setRescheduleSelection() {

        int selection = 0;
        if (!txtReasonReschdule.getText().toString().isEmpty()) {
            selection = Arrays.asList(reasonName).indexOf(txtReasonReschdule.getText().toString().trim());
        }
        new AlertDialog.Builder(ModifyClassRoomActivity.this).setTitle("Training")
                .setSingleChoiceItems(reasonName, selection, null)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", (dialog, whichButton) -> {
                    dialog.dismiss();
                    int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                    txtReasonReschdule.setText(reasonName[selectedPosition]);
                    if (txtReasonReschdule.getText().toString().contains("Other"))
                        otherReschedule.setVisibility(View.VISIBLE);
                    reasonIdString = reasonId[selectedPosition];
                })
                .show();

    }

    private void setCancelSelection() {

        int selection = 0;
        if (!txtReasonCancel.getText().toString().isEmpty()) {
            selection = Arrays.asList(reasonName).indexOf(txtReasonCancel.getText().toString().trim());
        }
        new AlertDialog.Builder(ModifyClassRoomActivity.this).setTitle("Training")
                .setSingleChoiceItems(reasonName, selection, null)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", (dialog, whichButton) -> {
                    dialog.dismiss();
                    int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                    txtReasonCancel.setText(reasonName[selectedPosition]);
                    if (txtReasonCancel.getText().toString().contains("Other"))
                        otherReschedule.setVisibility(View.VISIBLE);
                    reasonIdString = reasonId[selectedPosition];
                })
                .show();

    }

    private void getReasons() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            try {
                restService.getCancelOrReschedule().enqueue(new Callback<GetCancelOrRescheduleList>() {
                    @Override
                    public void onResponse(Call<GetCancelOrRescheduleList> call, Response<GetCancelOrRescheduleList> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getReasonsList() != null && response.body().getReasonsList().size() > 0) {
                                REASONS = response.body().getReasonsList();
                                reasonName = new String[REASONS.size()];
                                reasonId = new String[REASONS.size()];
                                for (int i = 0; i < response.body().getReasonsList().size(); i++) {
                                    reasonName[i] = REASONS.get(i).getName();
                                    reasonId[i] = REASONS.get(i).getId();
                                }
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } 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();
                            }
                        }
                    }

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

    private void setAllModifyData() {

        Log.e("SingleDataList", String.valueOf(GlobalData.scheduledDataList.get(0)));


        if (GlobalData.scheduledDataList != null && GlobalData.scheduledDataList.size() > 0) {
            lloutAddParticipant.setVisibility(View.GONE);
            btnAddParticipant.setVisibility(View.VISIBLE);
            trainingTitle.setEnabled(false);
            levelSpinner.setEnabled(false);

            if (GlobalData.scheduledDataList.get(0).getAdhocTraining().equalsIgnoreCase("1"))
                adHocSwitch.setChecked(true);
            else
                adHocSwitch.setChecked(false);

            if (GlobalData.scheduledDataList.get(0).getBusinessSegment().equalsIgnoreCase("2")) {
                rbScooter.setChecked(true);
                segment = "2";
            } else if (GlobalData.scheduledDataList.get(0).getBusinessSegment().equalsIgnoreCase("1")) {
                rbMotor.setChecked(true);
                segment = "1";
            } else {
                rbBoth.setChecked(true);
                segment = "3";
            }

            TRAINING_POSITION = Integer.parseInt(GlobalData.scheduledDataList.get(0).getLvlId());
            totalTime.setText(GlobalData.scheduledDataList.get(0).getTrainingTotalHours());
            noOfDays.setText(String.format("No. of training Days : " + GlobalData.scheduledDataList.get(0).getTrainingDays()));
            trainingTitle.setText(GlobalData.scheduledDataList.get(0).getTitle());
            trainingTitleId = GlobalData.scheduledDataList.get(0).getLvlId();
            description.setText(GlobalData.scheduledDataList.get(0).getScheduleName());
            startDate.setText(GlobalData.scheduledDataList.get(0).getStartdate());
            endDate.setText(GlobalData.scheduledDataList.get(0).getEnddate());

            strStartDate = GlobalData.scheduledDataList.get(0).getStartdate();
            strEndDate = GlobalData.scheduledDataList.get(0).getEnddate();

            if (GlobalData.scheduledDataList.get(0).getTrainingOtherTitle() != null)
                otherTitle.setText(GlobalData.scheduledDataList.get(0).getTrainingOtherTitle());

            String startTime = GlobalData.scheduledDataList.get(0).getStarttime();
            String endTime = GlobalData.scheduledDataList.get(0).getEndtime();


            if (GlobalData.scheduledDataList.get(0).getIsFeedback().equalsIgnoreCase("1")) {
                cbFeedback.setChecked(true);
            } else {
                cbFeedback.setChecked(false);
            }

            try {
                arrayFromTime = new JSONArray(startTime);

                for (int i = 0; i < arrayFromTime.length(); i++) {
                    String id = (String) arrayFromTime.get(i);
                    Log.e("ID", id);
                }

                arrayToTime = new JSONArray(endTime);

                for (int i = 0; i < arrayToTime.length(); i++) {
                    String id = (String) arrayToTime.get(i);
                    Log.e("ID", id);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            showTimeFrame(Integer.parseInt(GlobalData.scheduledDataList.get(0).getTrainingDays()));
            if (GlobalData.scheduledDataList.get(0).getVenueType().equalsIgnoreCase("1")) {
                venueView.setText("Dealer");
                venueAddress.setText(GlobalData.scheduledDataList.get(0).getVenueAddress());
                venueDealerLayout.setVisibility(View.VISIBLE);
            } else {
                venueView.setText("Others");
                venueDealerLayout.setVisibility(View.GONE);
                venueAddress.setText(GlobalData.scheduledDataList.get(0).getVenueAddress());
            }

            if (GlobalData.scheduledDataList.get(0).getParticipant() != null && GlobalData.scheduledDataList.get(0).getParticipant().size() > 0) {
                PARTICIPANTS = new ArrayList<>();
                for (int i = 0; i < GlobalData.scheduledDataList.get(0).getParticipant().size(); i++) {
                    DSE dse = new DSE();
                    dse.setSmpin(GlobalData.scheduledDataList.get(0).getParticipant().get(i).getSmpin());
                    dse.setUserid(GlobalData.scheduledDataList.get(0).getParticipant().get(i).getUserid());
                    dse.setFname(GlobalData.scheduledDataList.get(0).getParticipant().get(i).getName());
                    dse.setProfile(GlobalData.scheduledDataList.get(0).getParticipant().get(i).getProfilePhoto());
                    PARTICIPANTS.add(dse);
                }
            }
            adapter = new PartiPantAdapter();
            gridView.setAdapter(adapter);
            if (GlobalData.scheduledDataList.get(0).getAssessment() != null && GlobalData.scheduledDataList.get(0).getAssessment().size() > 0)
                for (int j = 0; j < GlobalData.scheduledDataList.get(0).getAssessment().size(); j++) {
                    if (GlobalData.scheduledDataList.get(0).getAssessment().get(j).getAssessmenttype().equalsIgnoreCase("pre")) {
                        cbPreAssessment.setChecked(true);

                        preAssesmentName.setText(GlobalData.scheduledDataList.get(0).getAssessment().get(j).getAssessmentname());
                        preAssessmentCount.setText(GlobalData.scheduledDataList.get(0).getAssessment().get(j).getTotalQuestion());
                        preAssessmentDuration.setText(GlobalData.scheduledDataList.get(0).getAssessment().get(j).getAssessmenttime());
                    } else {
                        cbPostAssessment.setChecked(true);
                        postAssesmentName.setText(GlobalData.scheduledDataList.get(0).getAssessment().get(j).getAssessmentname());
                        postAssessmentCount.setText(GlobalData.scheduledDataList.get(0).getAssessment().get(j).getTotalQuestion());
                        postAssessmentDuration.setText(GlobalData.scheduledDataList.get(0).getAssessment().get(j).getAssessmenttime());

                    }
                }

        }
    }

    private void publishTraining() {
        HashMap<String, String> map = new HashMap<>();
        map.put("title", String.valueOf(TRAINING_POSITION));
        map.put("description", description.getText().toString().trim());
        map.put("startdate", strStartDate);
        map.put("enddate", strEndDate);
        ArrayList<String> starttime = new ArrayList<>();
        ArrayList<String> endtime = new ArrayList<>();
        for (int i = 0; i < timeView.getChildCount(); i++) {
            View view = timeView.getChildAt(i);
            TextView txtFromTime = view.findViewById(R.id.txtFromTime);
            TextView txtToTime = view.findViewById(R.id.txtToTime);
            starttime.add(txtFromTime.getText().toString().trim());
            endtime.add(txtToTime.getText().toString().trim());
        }

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

        map.put("starttime", jsonElement.toString());
        map.put("endtime", jsonElement1.toString());

        ArrayList<CTAssessment> ctAssessments = new ArrayList<>();
        if (cbPreAssessment.isChecked()) {
            CTAssessment ctAssessment = new CTAssessment();
            ctAssessment.setName(preAssesmentName.getText().toString().trim());
            ctAssessment.setAssessment("pre");
            ctAssessment.setDuration(preAssessmentDuration.getText().toString().trim());
            ctAssessment.setQues_count(preAssessmentCount.getText().toString().trim());
            ctAssessments.add(ctAssessment);
        }

        if (cbPostAssessment.isChecked()) {
            CTAssessment ctAssessment1 = new CTAssessment();
            ctAssessment1.setName(postAssesmentName.getText().toString().trim());
            ctAssessment1.setAssessment("post");
            ctAssessment1.setDuration(postAssessmentDuration.getText().toString().trim());
            ctAssessment1.setQues_count(postAssessmentCount.getText().toString().trim());
            ctAssessments.add(ctAssessment1);
        }

        JsonElement jsonElement3 = gson.toJsonTree(
                ctAssessments, new TypeToken<ArrayList<CTAssessment>>() {
                }.getType());
        map.put("assessments", jsonElement3.toString());

        if (venueView.getText().toString().trim().equalsIgnoreCase("Dealer")) {
            map.put("venue_am", amEmail);
            map.put("venue_dealer", dealerCode);
            map.put("venue_type", "1");
            map.put("venue_address", venueAddress.getText().toString().trim());
        } else {
            map.put("venue_am", "");
            map.put("venue_dealer", "");
            map.put("venue_type", "0");
            map.put("venue_address", venueAddress.getText().toString().trim());
        }
        map.put("is_feedback", cbFeedback.isChecked() ? "1" : "0");
        map.put("training_total_hours", totalTime.getText().toString());

        ArrayList<String> dse = new ArrayList<>();
        for (DSE d : PARTICIPANTS) {
            dse.add(d.getUserid());
        }
        JsonElement jsonElement2 = gson.toJsonTree(
                dse, new TypeToken<ArrayList<String>>() {
                }.getType());

        map.put("dse", jsonElement2.toString());
        map.put("adhoc_training", adHocSwitch.isChecked() ? "1" : "0");
        map.put("business_segment", segment);

        map.put("training_other_title", otherTitle.getText().toString().trim());
        map.put("date_restriction", dateDifferReason == null ? "" : dateDifferReason);
        map.put("status", GlobalData.scheduledDataList.get(0).getStatus());
        map.put("schedule_id", GlobalData.scheduledDataList.get(0).getScheduleId());

        if (new UtilService().isNetworkAvailable(ModifyClassRoomActivity.this)) {
            progressDialog = new TransparentProgressDialog(ModifyClassRoomActivity.this);
            progressDialog.show();

            restService.sendAllUpdateTrainingToServer(map).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(@NotNull Call<CommonResponse> call, @NotNull Response<CommonResponse> response) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (response.body() != null) {
                        if (response.body().getResponse().equalsIgnoreCase("Success")) {
                            GlobalData.toast(ModifyClassRoomActivity.this, "Modified Successfully");
                            startActivity(new Intent(ModifyClassRoomActivity.this, ClassRoomTrainerTainingActivity.class));
                            finish();
                        } else {
                            GlobalData.toast(ModifyClassRoomActivity.this, response.body().getResponseText());
                        }

                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    } 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();
                        }
                    }
                }

                @Override
                public void onFailure(@NotNull Call<CommonResponse> call, @NotNull Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(ModifyClassRoomActivity.this, "Connection failure!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Toast.makeText(ModifyClassRoomActivity.this, "No internet connection!", Toast.LENGTH_SHORT).show();
        }

    }

    private boolean validate() {
        if (!rbScooter.isChecked() && !rbMotor.isChecked() && !rbBoth.isChecked()) {
            Toast.makeText(ModifyClassRoomActivity.this, "Please select business segment", Toast.LENGTH_SHORT).show();
            return false;
        }


        if (PARTICIPANTS == null || PARTICIPANTS.size() == 0) {
            Toast.makeText(ModifyClassRoomActivity.this, "Please select participants", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (startDate.getText().toString().trim().isEmpty() || endDate.getText().toString().trim().isEmpty()) {
            Toast.makeText(ModifyClassRoomActivity.this, "Please select training start and end date", Toast.LENGTH_SHORT).show();
            return false;
        }

        for (int i = 0; i < timeView.getChildCount(); i++) {
            View view = timeView.getChildAt(i);
            TextView dayCount = view.findViewById(R.id.dayCount);
            TextView txtFromTime = view.findViewById(R.id.txtFromTime);
            TextView txtToTime = view.findViewById(R.id.txtToTime);
            if (txtFromTime.getText().toString().trim().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select " + dayCount.getText().toString().trim() + " from time", Toast.LENGTH_SHORT).show();
                return false;
            }

            if (txtToTime.getText().toString().trim().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select " + dayCount.getText().toString().trim() + " to time", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        if (venueView.getText().toString().trim().equalsIgnoreCase("Dealer")) {
            if (venueAreaSpinner.getSelectedItemPosition() == 0) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select venue area manager", Toast.LENGTH_SHORT).show();
                return false;
            }

            if (venueDealerSpinner.getSelectedItemPosition() == 0) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select venue dealer location", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            if (venueAddress.getText().toString().trim().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please enter venue address", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        if (cbPreAssessment.isChecked()) {
            if (preAssesmentName.getText().toString().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please enter pre assessment name", Toast.LENGTH_SHORT).show();
                return false;
            }

            if (preAssessmentCount.getText().toString().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please enter pre assessment question count", Toast.LENGTH_SHORT).show();
                return false;
            }

            if (preAssessmentDuration.getText().toString().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please enter pre assessment question duration", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        if (cbPostAssessment.isChecked()) {
            if (postAssesmentName.getText().toString().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please enter post assessment name", Toast.LENGTH_SHORT).show();
                return false;
            }

            if (postAssessmentCount.getText().toString().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please enter post assessment question count", Toast.LENGTH_SHORT).show();
                return false;
            }

            if (postAssessmentDuration.getText().toString().isEmpty()) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please enter post assessment question duration", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        if (!radioCancel.isChecked() && !radioReschdule.isChecked() && !radioModify.isChecked()) {
            Toast.makeText(ModifyClassRoomActivity.this, "Please select reason", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!radioModify.isChecked()) {
            if (reasonIdString.equalsIgnoreCase("")) {
                Toast.makeText(ModifyClassRoomActivity.this, "Please select reason", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        return true;
    }

    private void showTimeFrame(int noOfDays) {
        timeView.removeAllViews();
        final String[] startTime = {""};
        final String[] endTime = {""};
        for (int i = 0; i < noOfDays; i++) {
            View view = LayoutInflater.from(ModifyClassRoomActivity.this).inflate(R.layout.time_item, null, false);
            TextView dayCount = view.findViewById(R.id.dayCount);
            dayCount.setText(String.format("Day %d", i + 1));

            txtFromTime = view.findViewById(R.id.txtFromTime);
            txtToTime = view.findViewById(R.id.txtToTime);
            txtToTime.setTag(txtFromTime);
            txtFromTime.setTag(i);

            txtFromTime.setOnClickListener(view1 -> {
                try {
                    txtToTime.setText("");
                    TextView mView = (TextView) view1;
                    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;
                        mView.setText(String.format("%s:%s", hour, min));
                        startTime[0] = mView.getText().toString();
                    }, false);
                    timePicker.setSelectableTimes(generateTimepoints(5));
                    timePicker.show(getSupportFragmentManager(), "TimePickerDialog");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            txtToTime.setOnClickListener(view1 -> {
                try {
                    TextView from = (TextView) view1.getTag();
                    String mFrom = from.getText().toString().trim();
                    if (mFrom.isEmpty()) {
                        Toast.makeText(this, "Please select from time", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    TextView mView = (TextView) view1;
                    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;
                        mView.setText(String.format("%s:%s", hour, min));


                        Date d1 = null;
                        long totalMinitues = 0, totalHours = 0;
                        String hours = "", minutes = "";

                        Date d2 = null;
                        for (int j = 0; j < timeView.getChildCount(); j++) {
                            View time = timeView.getChildAt(j);
                            TextView fromTime = time.findViewById(R.id.txtFromTime);
                            TextView toTime = time.findViewById(R.id.txtToTime);
                            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                            try {

                                d1 = format.parse(fromTime.getText().toString());
                                d2 = format.parse(toTime.getText().toString());
                                long diff = d2.getTime() - d1.getTime();
                                long diffMinutes = diff / (60 * 1000) % 60;
                                totalMinitues = totalMinitues + diffMinutes;
                                minutes = String.valueOf(totalMinitues);
                                if (totalMinitues < 10)
                                    minutes = "0" + minutes;
                                long diffHours = diff / (60 * 60 * 1000) % 24;
                                totalHours = totalHours + diffHours;
                                hours = String.valueOf(totalHours);
                                if (totalHours < 10)
                                    hours = "0" + hours;
                                Log.e(" hours, ", hours + ":" + hours);

                                totalTime.setText(hours + ":" + minutes);
                            } catch (Exception e) {

                            }
                        }

                    }, false);
                    timePicker.setSelectableTimes(generateTimepoints(5));
                    String[] split = mFrom.split(":");
                    int hour = Integer.parseInt(split[0]);
                    int minutes = Integer.parseInt(split[1]) + 5;
                    if (minutes >= 60) {
                        hour = hour + 1;
                        minutes = 5;
                    }
                    timePicker.setInitialSelection(hour, minutes);
                    timePicker.setMinTime(hour, minutes, 0);
                    timePicker.show(getSupportFragmentManager(), "TimePickerDialog");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            if (arrayFromTime != null && arrayFromTime.length() > 0) {
                try {
                    txtFromTime.setText((String) arrayFromTime.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (arrayToTime != null && arrayToTime.length() > 0) {
                try {
                    txtToTime.setText((String) arrayToTime.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            timeView.addView(view);
        }
    }

    private void getTrainingTitle() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            try {
                restService.getTitle().enqueue(new Callback<TrainingTitleLevel>() {
                    @Override
                    public void onResponse(@NotNull Call<TrainingTitleLevel> call, @NotNull Response<TrainingTitleLevel> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getLevelDataList() != null && response.body().getLevelDataList().size() > 0) {
                                TITLES = response.body().getLevelDataList();
                                TRAINING_TITLES = new String[TITLES.size()];
                                for (int i = 0; i < response.body().getLevelDataList().size(); i++) {
                                    TRAINING_TITLES[i] = TITLES.get(i).getLvlName();
                                }
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } 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();
                            }
                        }
                    }

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

    private void getVenueArea(String s) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            try {
                restService.getVenueAreaLocation(s).enqueue(new Callback<VenueAreaLocation>() {
                    @Override
                    public void onResponse(@NotNull Call<VenueAreaLocation> call, @NotNull Response<VenueAreaLocation> response) {

                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body() != null && response.body().getVenueAreaListList().size() > 0) {
                                VENUE_AREA = response.body().getVenueAreaListList();
                            } else {
                                VENUE_AREA = new ArrayList<>();
                            }
                            ArrayList<String> area = new ArrayList<>();
                            area.add("Select Area");
                            for (int i = 0; i < VENUE_AREA.size(); i++) {
                                area.add(VENUE_AREA.get(i).getAmName());
                            }
                            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(ModifyClassRoomActivity.this,
                                    R.layout.class_text_ms, area);
                            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_new);
                            venueAreaSpinner.setAdapter(spinnerArrayAdapter);

                            if (GlobalData.scheduledDataList != null && GlobalData.scheduledDataList.size() > 0) {
                                String text = GlobalData.scheduledDataList.get(0).getVenueAm();
                                text = text.replace("[", "");
                                text = text.replace("\"", "");
                                text = text.replace("]", "");
                                for (int k = 0; k < VENUE_AREA.size(); k++) {
                                    if (text.equalsIgnoreCase(VENUE_AREA.get(k).getAmEmail())) {
                                        venueAreaSpinner.setSelection(k + 1);
                                    }
                                }
                            }

                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } 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();
                            }
                        }
                    }

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

    private void getZoneDetails() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            try {
                restService.getZoneList().enqueue(new Callback<ZoneListResponse>() {
                    @Override
                    public void onResponse(@NotNull Call<ZoneListResponse> call, @NotNull Response<ZoneListResponse> response) {

                        if (response.body() != null && response.body().getStatus() == 200) {
                            String[] mZoneList;
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                mZoneList = new String[response.body().getData().size() + 1];
                                mZoneList[0] = "Select Zone";
                                for (int i = 1; i <= response.body().getData().size(); i++) {
                                    mZoneList[i] = response.body().getData().get(i - 1).getZone();
                                }
                            } else {
                                mZoneList = new String[2];
                                mZoneList[0] = "Select Zone";
                                mZoneList[1] = GlobalData.user.getData().getZone();
                            }
                            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(ModifyClassRoomActivity.this,
                                    R.layout.class_text_ms, mZoneList);
                            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_new);
                            zoneSpinner.setAdapter(spinnerArrayAdapter);
                            zoneSpinner.setSelection(Arrays.asList(mZoneList).indexOf(GlobalData.user.getData().getZone().trim()));
                        } 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(ModifyClassRoomActivity.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(ModifyClassRoomActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NotNull Call<ZoneListResponse> call, @NotNull Throwable t) {
                        GlobalData.showToast(ModifyClassRoomActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getRMDetails(String zone) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            progressDialog = new TransparentProgressDialog(ModifyClassRoomActivity.this);
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("zone", zone);

                restService.getRMList(map).enqueue(new Callback<RMResponse>() {
                    @Override
                    public void onResponse(@NotNull Call<RMResponse> call, @NotNull 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) {
                                RM_NAMES = new String[response.body().getData().size() + 1];
                                RM_NAMES[0] = "Select";
                                RM_IDS = new String[response.body().getData().size() + 1];
                                RM_IDS[0] = "-1";
                                for (int i = 1; i <= response.body().getData().size(); i++) {
                                    RM_NAMES[i] = response.body().getData().get(i - 1).getRm_name();
                                    RM_IDS[i] = response.body().getData().get(i - 1).getRm_email();
                                }
                            } else {
                                RM_NAMES = new String[1];
                                RM_NAMES[0] = "Select";
                                RM_IDS = new String[1];
                                RM_IDS[0] = "-1";
                            }
                            regionSpinner.setItems(RM_NAMES);
                            regionSpinner.hasNoneOption(true);
                            regionSpinner.setSelection(new int[]{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(ModifyClassRoomActivity.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(ModifyClassRoomActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

    private void getDSEDetails(ArrayList<String> dealerList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            progressDialog = new TransparentProgressDialog(ModifyClassRoomActivity.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(@NotNull Call<DSEResponse> call, @NotNull Response<DSEResponse> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null && response.body().getStatus() == 200) {
                            ArrayList<String> ids = new ArrayList<>();
                            for (int i = 0; i < PARTICIPANTS.size(); i++) {
                                ids.add(PARTICIPANTS.get(i).getSmpin());
                            }
                            DSE_LIST = response.body().getData();
                            if (DSE_LIST != null && DSE_LIST.size() > 0) {
                                DSE_NAMES = new String[DSE_LIST.size() + 1];
                                DSE_NAMES[0] = "Select";
                                DSE_IDS = new String[DSE_LIST.size() + 1];
                                DSE_IDS[0] = "-1";
                                for (int i = 1; i <= DSE_LIST.size(); i++) {
                                    DSE_NAMES[i] = DSE_LIST.get(i - 1).getName();
                                    DSE_IDS[i] = DSE_LIST.get(i - 1).getSmpin();
                                }

                                dseSpinner.setItems(DSE_NAMES);
                                dseSpinner.hasNoneOption(true);
                                if (ids.size() == 0) {
                                    dseSpinner.setSelection(new int[]{0});
                                } else {
                                    ArrayList<Integer> selections = new ArrayList<>();
                                    for (int j = 1; j < DSE_IDS.length; j++) {
                                        if (ids.contains(DSE_IDS[j])) {
                                            selections.add(j);
                                        }
                                    }
                                    int[] mSelection = new int[selections.size()];
                                    for (int i = 0; i < selections.size(); i++) {
                                        if (selections.get(i) != null) {
                                            mSelection[i] = selections.get(i);
                                        }
                                    }
                                    dseSpinner.setSelection(mSelection);
                                }
                            } else {
                                DSE_NAMES = new String[1];
                                DSE_NAMES[0] = "Select";
                                DSE_IDS = new String[1];
                                DSE_IDS[0] = "-1";
                                dseSpinner.setItems(DSE_NAMES);
                                dseSpinner.hasNoneOption(true);
                                dseSpinner.setSelection(new int[]{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(ModifyClassRoomActivity.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(ModifyClassRoomActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

    private void getDealerDetails(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            progressDialog = new TransparentProgressDialog(ModifyClassRoomActivity.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());
                map.put("segment", segment);
                restService.getDealerList(map).enqueue(new Callback<DealerResponse>() {
                    @Override
                    public void onResponse(@NotNull Call<DealerResponse> call, @NotNull 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) {
                                List<Integer> indics = dealerSpinner.getSelectedIndices();
                                ArrayList<String> ids = new ArrayList<>();
                                if (indics.size() != 0 && indics.get(0) != 0) {
                                    for (int i = 0; i < indics.size(); i++) {
                                        ids.add(DEALER_IDS[indics.get(i)]);
                                    }
                                }

                                DEALER_NAMES = new String[response.body().getData().size() + 1];
                                DEALER_NAMES[0] = "Select";
                                DEALER_IDS = new String[response.body().getData().size() + 1];
                                DEALER_IDS[0] = "-1";
                                for (int i = 1; i <= response.body().getData().size(); i++) {
                                    DEALER_NAMES[i] = response.body().getData().get(i - 1).getName();
                                    DEALER_IDS[i] = response.body().getData().get(i - 1).getDealer_code();
                                }
                                dealerSpinner.setItems(DEALER_NAMES);
                                dealerSpinner.hasNoneOption(true);

                                if (ids.size() == 0) {
                                    dealerSpinner.setSelection(new int[]{0});
                                } else {
                                    ArrayList<Integer> selections = new ArrayList<>();
                                    for (int j = 1; j < DEALER_IDS.length; j++) {
                                        if (ids.contains(DEALER_IDS[j])) {
                                            selections.add(j);
                                        }
                                    }
                                    int[] mSelection = new int[selections.size()];
                                    for (int i = 0; i < selections.size(); i++) {
                                        if (selections.get(i) != null) {
                                            mSelection[i] = selections.get(i);
                                        }
                                    }
                                    dealerSpinner.setSelection(mSelection);
                                }

                            } else {
                                DEALER_NAMES = new String[1];
                                DEALER_NAMES[0] = "Select";
                                DEALER_IDS = new String[1];
                                DEALER_IDS[0] = "-1";
                                dealerSpinner.setItems(DEALER_NAMES);
                                dealerSpinner.hasNoneOption(true);
                                dealerSpinner.setSelection(new int[]{0});

                                dseSpinner.setItems(emptyList);
                                dseSpinner.setSelection(new int[]{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(ModifyClassRoomActivity.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(ModifyClassRoomActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

    private void getVenueDealer(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            progressDialog = new TransparentProgressDialog(ModifyClassRoomActivity.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());
                map.put("segment", segment);
                restService.getDealerList(map).enqueue(new Callback<DealerResponse>() {
                    @Override
                    public void onResponse(@NotNull Call<DealerResponse> call, @NotNull 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) {
                                VENUE_DEALER = response.body().getData();
                            } else {
                                VENUE_DEALER = new ArrayList<>();
                            }
                            ArrayList<String> area = new ArrayList<>();
                            area.add("Select Dealer");
                            for (int i = 0; i < VENUE_DEALER.size(); i++) {
                                area.add(VENUE_DEALER.get(i).getName());
                            }
                            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(ModifyClassRoomActivity.this,
                                    R.layout.class_text_ms, area);
                            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_new);
                            venueDealerSpinner.setAdapter(spinnerArrayAdapter);
                            if (GlobalData.scheduledDataList != null && GlobalData.scheduledDataList.size() > 0) {
                                String text = GlobalData.scheduledDataList.get(0).getVenueDealer();
                                text = text.replace("[", "");
                                text = text.replace("\"", "");
                                text = text.replace("]", "");
                                for (int k = 0; k < VENUE_DEALER.size(); k++) {
                                    if (text.equalsIgnoreCase(VENUE_DEALER.get(k).getDealer_code())) {
                                        venueDealerSpinner.setSelection(k + 1);
                                        //  venueAddress.setText(VENUE_DEALER.get(k).getAddress());
                                    }
                                }
                            }
                        } 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(ModifyClassRoomActivity.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(ModifyClassRoomActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NotNull Call<DealerResponse> call, @NotNull Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(ModifyClassRoomActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getAMDetails(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            progressDialog = new TransparentProgressDialog(ModifyClassRoomActivity.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(@NotNull Call<AMResponse> call, @NotNull 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) {
                                List<Integer> indics = areaSpinner.getSelectedIndices();
                                ArrayList<String> ids = new ArrayList<>();
                                if (indics.size() != 0 && indics.get(0) != 0) {
                                    for (int i = 0; i < indics.size(); i++) {
                                        ids.add(AM_IDS[indics.get(i)]);
                                    }
                                }

                                AM_NAMES = new String[response.body().getData().size() + 1];
                                AM_NAMES[0] = "Select";
                                AM_IDS = new String[response.body().getData().size() + 1];
                                AM_IDS[0] = "-1";
                                for (int i = 1; i <= response.body().getData().size(); i++) {
                                    AM_NAMES[i] = response.body().getData().get(i - 1).getAm_name();
                                    AM_IDS[i] = response.body().getData().get(i - 1).getAm_email();
                                }

                                areaSpinner.setItems(AM_NAMES);
                                areaSpinner.hasNoneOption(true);
                                if (ids.size() == 0) {
                                    areaSpinner.setSelection(new int[]{0});
                                } else {
                                    ArrayList<Integer> selections = new ArrayList<>();
                                    for (int j = 1; j < AM_IDS.length; j++) {
                                        if (ids.contains(AM_IDS[j])) {
                                            selections.add(j);
                                        }
                                    }
                                    int[] mSelection = new int[selections.size()];
                                    for (int i = 0; i < selections.size(); i++) {
                                        if (selections.get(i) != null) {
                                            mSelection[i] = selections.get(i);
                                        }
                                    }
                                    areaSpinner.setSelection(mSelection);
                                }
                            } else {
                                AM_NAMES = new String[1];
                                AM_NAMES[0] = "Select";
                                AM_IDS = new String[1];
                                AM_IDS[0] = "-1";
                                areaSpinner.setItems(AM_NAMES);
                                areaSpinner.hasNoneOption(true);
                                areaSpinner.setSelection(new int[]{0});

                                dealerSpinner.setItems(emptyList);
                                dseSpinner.setItems(emptyList);

                                dealerSpinner.setSelection(0);
                                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(ModifyClassRoomActivity.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(ModifyClassRoomActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(ModifyClassRoomActivity.this)
                .setTitle("Training Modify")
                .setMessage("Are you sure to exit?")
                .setPositiveButton("Yes",
                        (dialog, which) -> {
                            startActivity(new Intent(ModifyClassRoomActivity.this, ClassRoomTrainerTainingActivity.class));
                            finish();
                            overridePendingTransition(R.anim.animation_f_enter,
                                    R.anim.animation_f_leave);
                        }).setNegativeButton("No", null).show();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    private void getRMBF(String zone) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(ModifyClassRoomActivity.this))) {
            progressDialog = new TransparentProgressDialog(ModifyClassRoomActivity.this);
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("zone", zone);

                restService.getRMList(map).enqueue(new Callback<RMResponse>() {
                    @Override
                    public void onResponse(@NotNull Call<RMResponse> call, @NotNull Response<RMResponse> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                RM_BF = response.body().getData();
                            }
                        }
                        if (RM_BF.size() > 0) {
                            ArrayList<String> rms = new ArrayList<>();
                            for (Region region : RM_BF) {
                                rms.add(region.getRm_email());
                            }
                            getAMBF(rms);
                        } else {
                            Toast.makeText(ModifyClassRoomActivity.this, "Error to fetch data", Toast.LENGTH_SHORT).show();
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                        }
                    }

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

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(ModifyClassRoomActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getAMBF(ArrayList<String> rmList) {
        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(@NotNull Call<AMResponse> call, @NotNull Response<AMResponse> response) {
                    if (response.body() != null && response.body().getStatus() == 200) {
                        if (response.body().getData() != null && response.body().getData().size() > 0) {
                            AM_BF = response.body().getData();
                        }
                    }
                    if (AM_BF.size() > 0) {
                        ArrayList<String> ams = new ArrayList<>();
                        for (Area area : AM_BF) {
                            ams.add(area.getAm_email());
                        }
                        getDealerBF(ams);
                    } else {
                        Toast.makeText(ModifyClassRoomActivity.this, "Error to fetch data", Toast.LENGTH_SHORT).show();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }
                }

                @Override
                public void onFailure(@NotNull Call<AMResponse> call, @NotNull Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(ModifyClassRoomActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });

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

    private void getDSEBF(ArrayList<String> dealerList) {
        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(@NotNull Call<DSEResponse> call, @NotNull Response<DSEResponse> 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) {
                            DSE_BF = response.body().getData();
                        }
                    }
                    if (DSE_BF.size() > 0) {
                        showPopup();
                    } else {
                        Toast.makeText(ModifyClassRoomActivity.this, "Error to fetch data", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(@NotNull Call<DSEResponse> call, @NotNull Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(ModifyClassRoomActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });

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

    @SuppressLint("ClickableViewAccessibility")
    private void showPopup() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

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

        View view = LayoutInflater.from(ModifyClassRoomActivity.this).inflate(R.layout.bf_popup, null, false);
        LinearLayout contentView = view.findViewById(R.id.contentView);
        contentView.removeAllViews();
        HorizontalScrollView headerScroll = view.findViewById(R.id.headerScroll);
        HorizontalScrollView contentScroll = view.findViewById(R.id.contentScroll);
        contentScroll.setTag(headerScroll);

        contentScroll.setOnScrollChangeListener((view12, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            HorizontalScrollView scrollView = (HorizontalScrollView) view12.getTag();
            scrollView.scrollTo(scrollX, scrollY);
        });

        for (Region region : RM_BF) {
            View regionView = LayoutInflater.from(ModifyClassRoomActivity.this).inflate(R.layout.bf_popup_item, null, false);
            TextView regionName = regionView.findViewById(R.id.regionName);
            regionName.setText(region.getRm_name());
            LinearLayout regionChild = regionView.findViewById(R.id.regionChild);
            regionChild.removeAllViews();
            for (Area area : AM_BF) {
                if (area.getRm_email().equalsIgnoreCase(region.getRm_email())) {
                    View areaView = LayoutInflater.from(ModifyClassRoomActivity.this).inflate(R.layout.bf_popup_item0, null, false);
                    TextView areName = areaView.findViewById(R.id.areName);
                    areName.setText(area.getAm_name());
                    LinearLayout areaChild = areaView.findViewById(R.id.areaChild);
                    areaChild.removeAllViews();
                    for (Dealer dealer : DEALER_BF) {
                        if (dealer.getAm_email().equalsIgnoreCase(area.getAm_email())) {
                            View dealerView = LayoutInflater.from(ModifyClassRoomActivity.this).inflate(R.layout.bf_popup_item1, null, false);
                            TextView dealerName = dealerView.findViewById(R.id.dealerName);
                            dealerName.setText(dealer.getName());
                            LinearLayout dealerChild = dealerView.findViewById(R.id.dealerChild);
                            dealerChild.removeAllViews();
                            for (DSE dse : DSE_BF) {
                                if (dse.getDealer_code().equalsIgnoreCase(dealer.getDealer_code())) {
                                    View dseView = LayoutInflater.from(ModifyClassRoomActivity.this).inflate(R.layout.bf_popup_text, null, false);
                                    CheckBox dseCheckbox = dseView.findViewById(R.id.dseCheckbox);
                                    dseCheckbox.setText(dse.getName());
                                    dseCheckbox.setTag(dse);
                                    dseCheckbox.setChecked(false);
                                    for (DSE mDse : PARTICIPANTS) {
                                        if (mDse.getSmpin().equalsIgnoreCase(dse.getSmpin())) {
                                            dseCheckbox.setChecked(true);
                                            break;
                                        }
                                    }

                                    dseCheckbox.setOnCheckedChangeListener((compoundButton, checked) -> {
                                        DSE mDse = (DSE) compoundButton.getTag();
                                        if (PARTICIPANTS == null || PARTICIPANTS.size() == 0) {
                                            PARTICIPANTS = new ArrayList<>();
                                        }
                                        boolean con = false;
                                        for (DSE sDse : PARTICIPANTS) {
                                            if (mDse.getSmpin().equalsIgnoreCase(sDse.getSmpin())) {
                                                con = true;
                                                break;
                                            }
                                        }
                                        if (checked) {
                                            if (!con) {
                                                PARTICIPANTS.add(mDse);
                                                adapter.notifyDataSetChanged();
                                            }
                                        } else {
                                            if (con) {
                                                PARTICIPANTS.remove(mDse);
                                                adapter.notifyDataSetChanged();
                                            }
                                        }
                                    });
                                    dealerChild.addView(dseView);
                                }
                            }
                            areaChild.addView(dealerView);
                        }
                    }
                    regionChild.addView(areaView);
                }
            }
            contentView.addView(regionView);
        }
        view.findViewById(R.id.actionBack).setOnClickListener(view1 -> {
            if (DSE_IDS != null) {
                ArrayList<String> ids = new ArrayList<>();
                for (int i = 0; i < PARTICIPANTS.size(); i++) {
                    ids.add(PARTICIPANTS.get(i).getSmpin());
                }
                if (ids.size() == 0) {
                    dseSpinner.setSelection(new int[]{0});
                } else {
                    ArrayList<Integer> selections = new ArrayList<>();
                    for (int j = 1; j < DSE_IDS.length; j++) {
                        if (ids.contains(DSE_IDS[j])) {
                            selections.add(j);
                        }
                    }
                    int[] mSelection = new int[selections.size()];
                    for (int i = 0; i < selections.size(); i++) {
                        if (selections.get(i) != null) {
                            mSelection[i] = selections.get(i);
                        }
                    }
                    dseSpinner.setSelection(mSelection);
                }
            }
            dialog.dismiss();
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(ModifyClassRoomActivity.this);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

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

    private void getDealerBF(ArrayList<String> rmList) {
        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());
            map.put("segment", segment);
            restService.getDealerList(map).enqueue(new Callback<DealerResponse>() {
                @Override
                public void onResponse(@NotNull Call<DealerResponse> call, @NotNull Response<DealerResponse> response) {

                    if (response.body() != null && response.body().getStatus() == 200) {
                        if (response.body().getData() != null && response.body().getData().size() > 0) {
                            DEALER_BF = response.body().getData();
                        }
                    }
                    if (DEALER_BF.size() > 0) {
                        ArrayList<String> dls = new ArrayList<>();
                        for (Dealer dealer : DEALER_BF) {
                            dls.add(dealer.getDealer_code());
                        }
                        getDSEBF(dls);
                    } else {
                        Toast.makeText(ModifyClassRoomActivity.this, "Error to fetch data", Toast.LENGTH_SHORT).show();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }
                }

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

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

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

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

    }

    class PartiPantAdapter extends BaseAdapter {

        PartiPantAdapter() {
        }

        @Override
        public int getCount() {
            return PARTICIPANTS.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) {
            ModifyClassRoomActivity.PartiPantAdapter.ViewHolder holder;
            if (convertView == null) {
                holder = new ModifyClassRoomActivity.PartiPantAdapter.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 = (ModifyClassRoomActivity.PartiPantAdapter.ViewHolder) convertView.getTag();
            }

            DSE dse = PARTICIPANTS.get(position);


            holder.name.setText(dse.getFullName());
            holder.smpin.setText(String.format("SMPIN : %s", dse.getSmpin()));
            holder.remove.setTag(dse);

            Glide.with(ModifyClassRoomActivity.this).load(dse.getProfile())
                    .thumbnail(Glide.with(ModifyClassRoomActivity.this).load(R.drawable.gif_loader))
                    .into(holder.userIcon);

            holder.remove.setOnClickListener(view -> {
                DSE mDse = (DSE) view.getTag();
                new AlertDialog.Builder(ModifyClassRoomActivity.this)
                        .setTitle(dse.getName())
                        .setMessage("Are you sure to remove?")
                        .setPositiveButton("Yes",
                                (dialog, which) -> {
                                    int pos = -1;
                                    for (int i = 0; i < DSE_LIST.size(); i++) {
                                        if (DSE_LIST.get(i).getSmpin().equalsIgnoreCase(mDse.getSmpin())) {
                                            pos = i + 1;
                                            break;
                                        }
                                    }

                                    if (pos != -1) {
                                        List<Integer> ids = dseSpinner.getSelectedIndices();
                                        int[] mSelection = new int[ids.size() - 1];
                                        int kk = 0;
                                        for (int k = 0; k < ids.size(); k++) {
                                            if (ids.get(k) != pos) {
                                                mSelection[kk] = ids.get(k);
                                                kk++;
                                            }
                                        }
                                        if (mSelection.length == 0) {
                                            dseSpinner.setSelection(new int[]{0});
                                        } else {
                                            dseSpinner.setSelection(mSelection);
                                        }
                                    }
                                    PARTICIPANTS.remove(mDse);
                                    notifyDataSetChanged();
                                }).setNegativeButton("No", null).show();
            });
            return convertView;
        }

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

}
