package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
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.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
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.GetAllAssesmentName;
import com.cygnusa.hyperm.wrappers.GetLevelDataList;
import com.cygnusa.hyperm.wrappers.RMResponse;
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 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 CreateClassRoomActivityNew extends AppCompatActivity {

    private final String[] VENUE_SELECTION = {"Dealer", "Other"};
    private final String[] emptyList = {"Select"};
    private final Calendar myCalendar = Calendar.getInstance();
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private final SimpleDateFormat setFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
    ImageButton levelSpinner;
    String strStartDate = "", strEndDate = "";
    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;
    String segment = "1";
    private ApiService restService;
    private TransparentProgressDialog progressDialog;
    private SwitchCompat adHocSwitch;
    private RadioButton rbScooter, rbMotor, rbBoth;
    private TextView trainingTitle, startDate, endDate, venueView, totalTime;
    private EditText description, venueAddress, preAssessmentCount, preAssessmentDuration,
            postAssessmentCount, postAssessmentDuration, otherTitle, preAssesmentName, postAssesmentName;
    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;
    private RelativeLayout trainingTitleView, venueLayout;
    private String[] TRAINING_TITLES, RM_NAMES, AM_NAMES, DEALER_NAMES, DSE_NAMES;
    private String[] RM_IDS, AM_IDS, DEALER_IDS, DSE_IDS;
    private List<GetLevelDataList> TITLES = new ArrayList<>();
    private int TRAINING_POSITION = -1;
    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 boolean isStartDate;
    private AlertDialog dialog;
    private EditText reason;
    private String dateDifferReason;
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            timeView.removeAllViews();

            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.YEAR, year);

            if (isStartDate) {
                startDate.setText(setFormat.format(myCalendar.getTime()));
                strStartDate = sdf.format(myCalendar.getTime());
                endDate.setText("");
                totalTime.setText("");
                //    totalMinitues = 0;
                //  totalHours = 0;
            } else {
                endDate.setText(setFormat.format(myCalendar.getTime()));
                totalTime.setText("");
                strEndDate = sdf.format(myCalendar.getTime());
                //totalMinitues = 0;
                //totalHours = 0;
                if (strStartDate == null || strStartDate.equalsIgnoreCase("")) {
                    GlobalData.toast(CreateClassRoomActivityNew.this, "Need to select start date first");
                    return;
                }
                LocalDate start = LocalDate.parse(strStartDate);
                LocalDate end = LocalDate.parse(strEndDate);
                long num = Days.daysBetween(start, end).getDays() + 1;
                String msg = "";
                if (Integer.parseInt(TITLES.get(TRAINING_POSITION).getTraining_days()) > num) {
                    msg = "The " + TITLES.get(TRAINING_POSITION).getLvlName()
                            + " Training title duration must be " + TITLES.get(TRAINING_POSITION).getTraining_days()
                            + " Days. Do you wants to reduce the duration of Training? If yes!";
                } else if (Integer.parseInt(TITLES.get(TRAINING_POSITION).getTraining_days()) < num) {
                    msg = "The " + TITLES.get(TRAINING_POSITION).getLvlName()
                            + " Training title duration must be " + TITLES.get(TRAINING_POSITION).getTraining_days()
                            + " Days. Do you wants to increase the duration of Training? If yes!";
                }
                if (msg.isEmpty()) {
                    showTimeFrame(Integer.parseInt(TITLES.get(TRAINING_POSITION).getTraining_days()));
                } else {
                    View mView = LayoutInflater.from(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Please enter reason", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        showTimeFrame(Math.toIntExact(num));
                        dialog.dismiss();
                    });

                    AlertDialog.Builder builder = new AlertDialog.Builder(CreateClassRoomActivityNew.this);
                    builder.setView(mView);
                    dialog = builder.create();
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                }
            }
        }
    };
    private TextView noOfDays;
    private int ZONE_POSITION = 0;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JodaTimeAndroid.init(this);
        setContentView(R.layout.activity_create_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", "UseCompatLoadingForDrawables"})
        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);
        trainingTitleView = findViewById(R.id.trainingTitleView);
        venueLayout = findViewById(R.id.venueLayout);

        rbScooter = findViewById(R.id.rbScooter);
        rbMotor = findViewById(R.id.rbMotor);
        rbBoth = findViewById(R.id.rbBoth);
        rbScooter.setChecked(false);

        rbScooter.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                enableAllData();
                segment = "2";
                if (TRAINING_POSITION != -1) {
                    getAssessmentNames(segment);
                }
            }
        });

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

        rbBoth.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                enableAllData();
                segment = "3";
                if (TRAINING_POSITION != -1) {
                    getAssessmentNames(segment);
                }
            }
        });

        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);
        totalTime = findViewById(R.id.totalTime);
        totalTime.setVisibility(View.VISIBLE);
        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);

        noOfDays = findViewById(R.id.noOfDays);

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

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

        venueDealerLayout.setVisibility(View.GONE);

        btnAddParticipant.setOnClickListener(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(true);
        cbFeedback.setChecked(true);
        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");
                    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(CreateClassRoomActivityNew.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());
                    getVenueDealer(area);
                }
            }

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

            }
        });


        trainingTitle.setEnabled(false);
        startDate.setEnabled(false);
        venueDealerLayout.setEnabled(false);
        venueDealerLayout.setEnabled(false);
        venueDealerLayout.setEnabled(false);
        description.setEnabled(false);
        postAssesmentLayout.setEnabled(false);
        preAssessmentLayout.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);
        trainingTitleView.setEnabled(false);

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

        postAssesmentName.setEnabled(false);
        postAssessmentCount.setEnabled(false);
        postAssessmentDuration.setEnabled(false);
        btnAddParticipant.setEnabled(false);
        startDate.setEnabled(false);
        endDate.setEnabled(false);
        startDate.setClickable(false);
        endDate.setEnabled(false);
        PARTICIPANTS = new ArrayList<>();

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

        zoneSpinner.setEnabled(false);
        areaSpinner.setEnabled(false);
        regionSpinner.setEnabled(false);
        dealerSpinner.setEnabled(false);
        dseSpinner.setEnabled(false);
        venueLayout.setEnabled(false);

        trainingTitle.setText("");
        description.setText("");
        regionSpinner.setSelection(0);
        areaSpinner.setSelection(0);
        dealerSpinner.setSelection(0);
        dseSpinner.setSelection(0);
        startDate.setText("");
        endDate.setText("");
        venueView.setText("");
        preAssesmentName.setText("");
        postAssesmentName.setText("");
        preAssessmentDuration.setText("");
        postAssessmentDuration.setText("");
        preAssessmentCount.setText("");
        postAssessmentCount.setText("");


        venueDealerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                if (pos == 0) {
                    venueAddress.setText("");
                } else {
                    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) {
                if (ZONE_POSITION == position) {
                    getRMDetails(zoneSpinner.getSelectedItem().toString());
                    getVenueArea(zoneSpinner.getSelectedItem().toString());
                    return;
                }

                if (GlobalData.user.getData().getZone().equalsIgnoreCase(zoneSpinner.getSelectedItem().toString())) {
                    getRMDetails(zoneSpinner.getSelectedItem().toString());
                } else {
                    openAlertPopup(position);
                }


            }

            @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) {

            }
        });

        trainingTitleView.setOnClickListener(view ->
        {
            int selection = 0;
            if (!trainingTitle.getText().toString().isEmpty()) {
                selection = Arrays.asList(TRAINING_TITLES).indexOf(trainingTitle.getText().toString().trim());
            }
            new AlertDialog.Builder(CreateClassRoomActivityNew.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]);
                        TRAINING_POSITION = selectedPosition;

                        clearAllData();

                        noOfDays.setText(String.format("No. of training Days : %d", Integer.parseInt(TITLES.get(TRAINING_POSITION).getTraining_days())));

                        if (TRAINING_TITLES[selectedPosition].toLowerCase().contains("other")) {
                            otherLayout.setVisibility(View.VISIBLE);
                            preAssesmentName.setText("");
                            postAssesmentName.setText("");
                            getAssessmentNames(segment);
                        } else {
                            otherLayout.setVisibility(View.GONE);
                            getAssessmentNames(segment);
                        }
                    })
                    .show();
        });

        findViewById(R.id.popupView).

                setOnClickListener(view ->

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

                    if (TRAINING_POSITION == -1) {
                        Toast.makeText(CreateClassRoomActivityNew.this, "Please select training title", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (TRAINING_TITLES[TRAINING_POSITION].toLowerCase().contains("other")) {
                        if (otherTitle.getText().toString().isEmpty()) {
                            Toast.makeText(CreateClassRoomActivityNew.this, "Please enter other training title", 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);

        venueLayout.setOnClickListener(view ->
        {
            int selection = 0;
            if (!venueView.getText().toString().isEmpty()) {
                selection = Arrays.asList(VENUE_SELECTION).indexOf(venueView.getText().toString().trim());
            }
            new AlertDialog.Builder(CreateClassRoomActivityNew.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]);
                        if (selectedPosition == 0) {
                            venueDealerLayout.setVisibility(View.VISIBLE);
                        } else {
                            venueDealerLayout.setVisibility(View.GONE);
                            // venueAddress.setEnabled(true);
                        }
                    })
                    .show();
        });

        findViewById(R.id.actionSave).setOnClickListener(view ->
        {
            if (validate()) {
                publishTraining(0);
            }
        });

        findViewById(R.id.actionPublish).setOnClickListener(view -> {
            if (validate()) {
                View mView = LayoutInflater.from(CreateClassRoomActivityNew.this).inflate(R.layout.publish_alert, null, false);
                TextView mTitle = mView.findViewById(R.id.mTitle);
                mTitle.setText(String.format("(%s - %s)", TRAINING_TITLES[TRAINING_POSITION], startDate.getText().toString().trim()));

                mView.findViewById(R.id.actionCancel).setOnClickListener(view12 -> dialog.dismiss());

                mView.findViewById(R.id.actionSubmit).setOnClickListener(view1 -> {
                    publishTraining(1);
                    dialog.dismiss();
                });

                AlertDialog.Builder builder = new AlertDialog.Builder(CreateClassRoomActivityNew.this);
                builder.setView(mView);
                dialog = builder.create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }
        });

        startDate.setOnClickListener(v ->

        {
            if (TRAINING_POSITION == -1) {
                Toast.makeText(CreateClassRoomActivityNew.this, "Please select Training", Toast.LENGTH_SHORT).show();
                return;
            }
            isStartDate = true;
            DatePickerDialog dialog = new DatePickerDialog(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Please select start date.", Toast.LENGTH_SHORT).show();
                return;
            }
            isStartDate = false;
            DatePickerDialog dialog = new DatePickerDialog(CreateClassRoomActivityNew.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();

        });

    }

    private void clearAllData() {
        trainingTitle.setEnabled(true);
        startDate.setEnabled(true);
        venueDealerLayout.setEnabled(true);
        venueDealerLayout.setEnabled(true);
        venueDealerLayout.setEnabled(true);
        description.setEnabled(true);
        postAssesmentLayout.setEnabled(true);
        preAssessmentLayout.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);

        trainingTitleView.setEnabled(true);

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

        postAssesmentName.setEnabled(true);
        postAssessmentCount.setEnabled(true);
        postAssessmentDuration.setEnabled(true);
        btnAddParticipant.setEnabled(true);
        startDate.setEnabled(true);
        endDate.setEnabled(true);
        startDate.setClickable(true);
        endDate.setEnabled(true);
        PARTICIPANTS = new ArrayList<>();

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

        zoneSpinner.setEnabled(true);
        areaSpinner.setEnabled(true);
        regionSpinner.setEnabled(true);
        dealerSpinner.setEnabled(true);
        dseSpinner.setEnabled(true);
        venueLayout.setEnabled(true);

        description.setText("");
        regionSpinner.setSelection(0);
        areaSpinner.setSelection(0);
        dealerSpinner.setSelection(0);
        dseSpinner.setSelection(0);
        startDate.setText("");
        endDate.setText("");
        venueView.setText("");
        preAssesmentName.setText("");
        postAssesmentName.setText("");
        preAssessmentDuration.setText("");
        postAssessmentDuration.setText("");
        preAssessmentCount.setText("");
        postAssessmentCount.setText("");
        adapter.notifyDataSetChanged();
    }

    private void enableAllData() {
        trainingTitle.setEnabled(true);
        startDate.setEnabled(true);
        venueDealerLayout.setEnabled(true);
        venueDealerLayout.setEnabled(true);
        venueDealerLayout.setEnabled(true);
        description.setEnabled(true);
        postAssesmentLayout.setEnabled(true);
        preAssessmentLayout.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);

        trainingTitleView.setEnabled(true);

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

        postAssesmentName.setEnabled(true);
        postAssessmentCount.setEnabled(true);
        postAssessmentDuration.setEnabled(true);
        btnAddParticipant.setEnabled(true);
        startDate.setEnabled(true);
        endDate.setEnabled(true);
        startDate.setClickable(true);
        endDate.setEnabled(true);
        PARTICIPANTS = new ArrayList<>();

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

        zoneSpinner.setEnabled(true);
        areaSpinner.setEnabled(true);
        regionSpinner.setEnabled(true);
        dealerSpinner.setEnabled(true);
        dseSpinner.setEnabled(true);
        venueLayout.setEnabled(true);

        trainingTitle.setText("");
        description.setText("");
        regionSpinner.setSelection(0);
        areaSpinner.setSelection(0);
        dealerSpinner.setSelection(0);
        dseSpinner.setSelection(0);
        startDate.setText("");
        endDate.setText("");
        venueView.setText("");
        preAssesmentName.setText("");
        postAssesmentName.setText("");
        preAssessmentDuration.setText("");
        postAssessmentDuration.setText("");
        preAssessmentCount.setText("");
        postAssessmentCount.setText("");
        adapter.notifyDataSetChanged();
    }

    @SuppressLint("SetTextI18n")
    private void openAlertPopup(int position) {
        final Dialog aDialog = new Dialog(this);
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_alert_change);
        aDialog.setCancelable(true);
        TextView aAlertMessage = aDialog.findViewById(R.id.txt_alert_message);
        aAlertMessage.setText("Are you sure? if you want to change the Zone, your selected data will be reset");
        aDialog.show();
        Button btnYes = aDialog.findViewById(R.id.btn_ok);
        Button btnNo = aDialog.findViewById(R.id.btn_cancel);
        btnYes.setOnClickListener(view -> {
            aDialog.dismiss();
            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();
            ZONE_POSITION = position;
            if (position != 0) {
                getRMDetails(zoneSpinner.getSelectedItem().toString());
            }
            getVenueArea(zoneSpinner.getSelectedItem().toString());
        });
        btnNo.setOnClickListener(arg0 -> {
            aDialog.dismiss();
            zoneSpinner.setSelection(ZONE_POSITION);
        });
    }

    private void getAssessmentNames(String segment) {
        restService.getAssessmentName(TITLES.get(TRAINING_POSITION).getLvlId(), segment).enqueue(new Callback<GetAllAssesmentName>() {
            @Override
            public void onResponse(@NotNull Call<GetAllAssesmentName> call, @NotNull Response<GetAllAssesmentName> response) {
                if (response.body() != null) {
                    if (response.body().getAssessmentName() != null) {
                        preAssesmentName.setText(response.body().getAssessmentName().getPre());
                        postAssesmentName.setText(response.body().getAssessmentName().getPost());
                    }
                } 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<GetAllAssesmentName> call, @NotNull Throwable t) {

            }
        });
    }

    private void publishTraining(int status) {
        HashMap<String, String> map = new HashMap<>();
        map.put("title", TITLES.get(TRAINING_POSITION).getLvlId());
        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", VENUE_AREA.get(venueAreaSpinner.getSelectedItemPosition() - 1).getAmEmail());
            map.put("venue_dealer", VENUE_DEALER.get(venueDealerSpinner.getSelectedItemPosition() - 1).getDealer_code());
            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);

        if (TRAINING_TITLES[TRAINING_POSITION].toLowerCase().contains("other")) {
            map.put("training_other_title", otherTitle.getText().toString().trim());
        } else {
            map.put("training_other_title", "");
        }
        map.put("date_restriction", dateDifferReason == null ? "" : dateDifferReason);
        map.put("status", String.valueOf(status));

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

            restService.sendAllTrainingToServer(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")) {
                            if (status == 1)
                                GlobalData.toast(CreateClassRoomActivityNew.this, "Training published successfully");
                            else
                                GlobalData.toast(CreateClassRoomActivityNew.this, "Training saved successfully");
                            startActivity(new Intent(CreateClassRoomActivityNew.this, ClassRoomTrainerTainingActivity.class));
                            finish();
                        } else {
                            GlobalData.toast(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection failure!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Toast.makeText(CreateClassRoomActivityNew.this, "No internet connection!", Toast.LENGTH_SHORT).show();
        }

    }

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

        if (TRAINING_POSITION == -1) {
            Toast.makeText(CreateClassRoomActivityNew.this, "Please select training title", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TRAINING_TITLES[TRAINING_POSITION].toLowerCase().contains("other")) {
            if (otherTitle.getText().toString().isEmpty()) {
                Toast.makeText(CreateClassRoomActivityNew.this, "Please enter other training title", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

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

        if (startDate.getText().toString().trim().isEmpty() || endDate.getText().toString().trim().isEmpty()) {
            Toast.makeText(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Please select " + dayCount.getText().toString().trim() + " from time", Toast.LENGTH_SHORT).show();
                return false;
            }

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

        if (venueView.getText().toString().trim().equalsIgnoreCase("select")) {
            Toast.makeText(CreateClassRoomActivityNew.this, "Please select venue Location", Toast.LENGTH_SHORT).show();
            return false;
        }

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

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

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

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

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

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

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

            if (postAssessmentDuration.getText().toString().isEmpty()) {
                Toast.makeText(CreateClassRoomActivityNew.this, "Please enter post assessment question duration", 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(CreateClassRoomActivityNew.this).inflate(R.layout.time_item, null, false);
            TextView dayCount = view.findViewById(R.id.dayCount);
            dayCount.setText(String.format("Day %d", i + 1));

            TextView txtFromTime = view.findViewById(R.id.txtFromTime);
            TextView 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();
                }

            });

            timeView.addView(view);
        }
    }

    private void getTrainingTitle() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.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 zone) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.this))) {
            try {

                restService.getVenueAreaLocation(zone).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");
                            for (int i = 0; i < VENUE_AREA.size(); i++) {
                                area.add(VENUE_AREA.get(i).getAmName());
                            }
                            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(CreateClassRoomActivityNew.this,
                                    R.layout.class_text_ms, area);
                            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_new);
                            venueAreaSpinner.setAdapter(spinnerArrayAdapter);
                        } 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(CreateClassRoomActivityNew.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<>(CreateClassRoomActivityNew.this,
                                    R.layout.class_text_ms, mZoneList);
                            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_new);
                            zoneSpinner.setAdapter(spinnerArrayAdapter);
                            ZONE_POSITION = Arrays.asList(mZoneList).indexOf(GlobalData.user.getData().getZone().trim());
                            zoneSpinner.setSelection(ZONE_POSITION);
                        } 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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getRMDetails(String zone) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.this))) {
            progressDialog = new TransparentProgressDialog(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getDSEDetails(ArrayList<String> dealerList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.this))) {
            progressDialog = new TransparentProgressDialog(CreateClassRoomActivityNew.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", "");
                map.put("segment", segment);

                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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getDealerDetails(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.this))) {
            progressDialog = new TransparentProgressDialog(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getVenueDealer(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.this))) {
            progressDialog = new TransparentProgressDialog(CreateClassRoomActivityNew.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");
                            for (int i = 0; i < VENUE_DEALER.size(); i++) {
                                area.add(VENUE_DEALER.get(i).getName());
                            }
                            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(CreateClassRoomActivityNew.this,
                                    R.layout.class_text_ms, area);
                            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_new);
                            venueDealerSpinner.setAdapter(spinnerArrayAdapter);
                        } 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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    private void getAMDetails(ArrayList<String> rmList) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.this))) {
            progressDialog = new TransparentProgressDialog(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

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

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(CreateClassRoomActivityNew.this)
                .setTitle("Training Creation")
                .setMessage("Are you sure to exit?")
                .setPositiveButton("Yes",
                        (dialog, which) -> {
                            startActivity(new Intent(CreateClassRoomActivityNew.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) {
            startActivity(new Intent(CreateClassRoomActivityNew.this, ClassRoomTrainerTainingActivity.class));
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private void getRMBF(String zone) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(CreateClassRoomActivityNew.this))) {
            progressDialog = new TransparentProgressDialog(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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", "");
            map.put("segment", segment);

            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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.this);
        progressDialog.show();

        View view = LayoutInflater.from(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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(CreateClassRoomActivityNew.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) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.participant_item, null);
                holder.name = convertView.findViewById(R.id.name);
                holder.remove = convertView.findViewById(R.id.remove);
                holder.smpin = convertView.findViewById(R.id.smpin);
                holder.userIcon = convertView.findViewById(R.id.userIcon);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            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(CreateClassRoomActivityNew.this).load(dse.getProfile())
                    .thumbnail(Glide.with(CreateClassRoomActivityNew.this).load(R.drawable.gif_loader))
                    .into(holder.userIcon);

            holder.remove.setOnClickListener(view -> {
                DSE mDse = (DSE) view.getTag();
                new AlertDialog.Builder(CreateClassRoomActivityNew.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;
        }
    }
}
