package com.ttiglobal.inttilectgpchat.training.activities;

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

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

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

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

public class AddParticipantActivity extends AppCompatActivity {

    public static Schedules SCHEDULE = new Schedules();
    private MultiSelectSpinner regionSpinner, areaSpinner, dealerSpinner, dseSpinner;
    private TransparentProgressDialog progressDialog;

    private LinearLayout llout_region, llout_am, llout_dealer;


    private ApiService restService;

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

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

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

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

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

    private List<Integer> NAMES = new ArrayList<>();
    private ArrayList<DSE> DSE_LIST = new ArrayList<>();
    private PartiPantAdapter adapter;
    private ArrayList<String> IDS = new ArrayList<>();

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

        TextView dateTime = findViewById(R.id.dateTime);
        regionSpinner = findViewById(R.id.regionSpinner);
        areaSpinner = findViewById(R.id.areaSpinner);
        dealerSpinner = findViewById(R.id.dealerSpinner);
        dseSpinner = findViewById(R.id.dseSpinner);
        GridView participantList = findViewById(R.id.participantList);
        adapter = new PartiPantAdapter();
        participantList.setAdapter(adapter);
        TextView title = findViewById(R.id.title);
        title.setText(SCHEDULE.getTitle());
        dateTime.setText(SCHEDULE.getDateTime());

        llout_region = findViewById(R.id.llout_region);
        llout_am = findViewById(R.id.llout_am);
        llout_dealer = findViewById(R.id.llout_dealer);

        for (DSE dse : SCHEDULE.getUserlist()) {
            IDS.add(dse.getUserid().trim());
        }

        Button addParticipant = findViewById(R.id.addParticipant);

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

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

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

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

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

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

            }
        });

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

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

            }
        });

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

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

            }
        });

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

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

            }
        });

        if (!GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
            if (!GlobalData.user.getData().getRole().equalsIgnoreCase("7")) {
                if (!GlobalData.user.getData().getRole().equalsIgnoreCase("14")) {
                    getRMDetails();
                } else {

                    mDealerList[0] = GlobalData.user.getData().getName();
                    mDealerId[0] = GlobalData.user.getData().getDealer().getDealer_code();

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

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

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

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

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

//        getRMDetails();
        addParticipant.setOnClickListener(v -> addParticipant());
    }

    private void addParticipant() {

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

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

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

        HashMap<String, String> map = new HashMap<>();
        map.put("userid", jsonElement.toString());
        map.put("trainingid", SCHEDULE.getId());

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

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

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

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

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

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

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

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

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

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

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

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null && response.body().getStatus() == 200) {

                            ArrayList<DSE> tempDse = response.body().getData();
                            DSE_LIST = new ArrayList<>();
                            for (DSE dse : tempDse) {
                                if (!IDS.contains(dse.getUserid())) {
                                    DSE_LIST.add(dse);
                                }
                            }

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

                                dseSpinner.setItems(mDSEList);
                                dseSpinner.hasNoneOption(true);
                                dseSpinner.setSelection(new int[]{0});
                                NAMES = new ArrayList<>();
                                dseSpinner.setSelection(0);
                            } else {
                                mDSEList = new String[1];
                                mDSEList[0] = "Select";
                                mDSEId = new String[1];
                                mDSEId[0] = "-1";
                                dseSpinner.setItems(mDSEList);
                                dseSpinner.hasNoneOption(true);
                                dseSpinner.setSelection(new int[]{0});
                                NAMES = new ArrayList<>();
                                dseSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(AddParticipantActivity.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(AddParticipantActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

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

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

                                regionSpinner.setItems(mRegionList);
                                regionSpinner.hasNoneOption(true);
                                regionSpinner.setSelection(new int[]{0});
                                regionSpinner.setSelection(0);
                            } else {
                                mRegionList = new String[1];
                                mRegionList[0] = "Select";
                                mRegionId = new String[1];
                                mRegionId[0] = "-1";
                                regionSpinner.setItems(mRegionList);
                                regionSpinner.hasNoneOption(true);
                                regionSpinner.setSelection(new int[]{0});
                                regionSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(AddParticipantActivity.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(AddParticipantActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

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

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

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

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

                                areaSpinner.setItems(mAMList);
                                areaSpinner.hasNoneOption(true);
                                areaSpinner.setSelection(new int[]{0});
                                areaSpinner.setSelection(0);
                            } else {
                                mAMList = new String[1];
                                mAMList[0] = "Select";
                                mAMId = new String[1];
                                mAMId[0] = "-1";
                                areaSpinner.setItems(mAMList);
                                areaSpinner.hasNoneOption(true);
                                areaSpinner.setSelection(new int[]{0});
                                areaSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(AddParticipantActivity.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(AddParticipantActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

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

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

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

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

                                dealerSpinner.setItems(mDealerList);
                                dealerSpinner.hasNoneOption(true);
                                dealerSpinner.setSelection(new int[]{0});
                                dealerSpinner.setSelection(0);
                            } else {
                                mDealerList = new String[1];
                                mDealerList[0] = "Select";
                                mDealerId = new String[1];
                                mDealerId[0] = "-1";
                                dealerSpinner.setItems(mDealerList);
                                dealerSpinner.hasNoneOption(true);
                                dealerSpinner.setSelection(new int[]{0});
                                dealerSpinner.setSelection(0);
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(AddParticipantActivity.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(AddParticipantActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

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

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

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

    class PartiPantAdapter extends BaseAdapter {

        PartiPantAdapter() {

        }

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

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

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

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

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

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

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

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