package com.gingersoft.gsa.cloud.ui.adapter;

import android.util.SparseBooleanArray;
import android.widget.CheckBox;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.gingersoft.gsa.cloud.ui.R;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;

public class MultipleChoiceAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

    private SparseBooleanArray sparseArray;
    private List<Integer> defaultChecks;

    public MultipleChoiceAdapter(@Nullable List data, List<Integer> defaultChecks) {
        super(R.layout.item_multiple_choice_layout, data);
        sparseArray = new SparseBooleanArray();
        this.defaultChecks = defaultChecks;
    }

    @Override
    protected void convert(@NotNull BaseViewHolder baseViewHolder, String s) {
        CheckBox checkBox = baseViewHolder.getView(R.id.cb_dialog_multiply_choice);
        baseViewHolder.setText(R.id.tv_dialog_multiply_choice_name, s);
        if (defaultChecks.contains(baseViewHolder.getAdapterPosition())) {
            checkBox.setChecked(true);
            sparseArray.put(baseViewHolder.getAdapterPosition(), true);
        } else {
            checkBox.setChecked(false);
        }
        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                sparseArray.put(baseViewHolder.getAdapterPosition(), true);
            } else {
                sparseArray.delete(baseViewHolder.getAdapterPosition());
            }
        });
        baseViewHolder.itemView.setOnClickListener(v -> checkBox.setChecked(!checkBox.isChecked()));
    }

    public String getChecked(){
        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0; i < sparseArray.size(); i++) {
            stringBuffer.append(sparseArray.keyAt(i));
            stringBuffer.append(",");
        }
        return stringBuffer.toString();
    }
}
