package com.rdiot.yx485.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;

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

import com.bumptech.glide.Glide;
import com.rdiot.yx485.R;
import com.rdiot.yx485.bean.EditDeviceReplyBean.DataBean.DeviceBean;
import com.rdiot.yx485.databinding.DeviceItemListContentBinding;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.webview.WebViewActivity;

import java.util.List;

public class DeviceListAdapter extends RecyclerView.Adapter<DeviceListAdapter.ViewHolder> {
    private final Context mContext;
    public List<DeviceBean> mList;

    private OnClickDeleteListener mDeleteListener;

    public DeviceListAdapter(Context context, List<DeviceBean> list) {
        mContext = context;
        mList = list;
    }

    public void setDeleteListener(OnClickDeleteListener deleteListener) {
        mDeleteListener = deleteListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        DeviceItemListContentBinding binding = DeviceItemListContentBinding.inflate(LayoutInflater.from(mContext), parent, false);
        return new ViewHolder(binding);
    }

    @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 interface OnClickDeleteListener {
        void onClickDelete(String deviceId);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private final DeviceItemListContentBinding mBinding;

        ViewHolder(DeviceItemListContentBinding itemView) {
            super(itemView.getRoot());
            mBinding = itemView;
        }

        void bindData(int position) {
            DeviceBean device = mList.get(position);
            if (!TextUtils.isEmpty(device.name)) {
                mBinding.name.setText(device.name);
            }
            mBinding.stae.setText(device.is_master ? "设备在线" : "设备离线");
            if (!TextUtils.isEmpty(device.icon)) {
                Glide.with(mContext)
                        .load(Url.BASE_URL + device.icon)
                        .error(Glide.with(itemView.getContext()).load(R.drawable.find_d))
                        .into(mBinding.image);
            }
            mBinding.deleteButton.setOnClickListener(v -> {
                if (mDeleteListener != null) {
                    mDeleteListener.onClickDelete(device.record_id);
                }
            });
            mBinding.layoutContainer.setOnClickListener(v -> {
                if (!TextUtils.isEmpty(device.detail_url)) {
                    WebViewActivity.newIntent(mContext, device.detail_url, null);
                }
            });
        }
    }
}