package com.rdiot.yx485.adapter;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.rdiot.yx485.R;
import com.rdiot.yx485.bean.DeviceRoomListBean;

import java.util.List;

public class DeviceRoomAdapter extends RecyclerView.Adapter<DeviceRoomAdapter.ViewHolder> {

    public List<DeviceRoomListBean.RoomBean> mList;
    public int mSelectedPosition = -1;//初始化为负值，表示默认不选中任何选项

    public DeviceRoomAdapter(List<DeviceRoomListBean.RoomBean> data) {
        mList = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.device_room_content, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.setIsRecyclable(false);
        holder.bindData(position);
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    public DeviceRoomListBean.RoomBean getSelectedRoom() {
        if (mList.isEmpty() || mSelectedPosition == -1 || mList.size() <= mSelectedPosition) {
            return null;
        }

        return mList.get(mSelectedPosition);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView name;
        private final CheckBox checkBox;

        ViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            checkBox = itemView.findViewById(R.id.checkBox);
        }

        @SuppressLint("NotifyDataSetChanged")
        public void bindData(int position) {
            DeviceRoomListBean.RoomBean roomBean = mList.get(position);
            if (roomBean == null) {
                return;
            }

            if (!TextUtils.isEmpty(roomBean.name)) {
                name.setText(roomBean.name);
            }

            checkBox.setChecked(position == mSelectedPosition);
            checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
                if (b) {
                    mSelectedPosition = position;
                } else {
                    mSelectedPosition = -1;
                }
                notifyDataSetChanged();
            });
        }
    }
}