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.GoodListBean.DataBean.GoodBean;
import com.rdiot.yx485.databinding.ViewDiscoverItemBinding;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.webview.WebViewActivity;

import java.util.List;

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

    private final List<GoodBean> mList;
    private final Context mContext;

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

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ViewDiscoverItemBinding binding = ViewDiscoverItemBinding.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 class ViewHolder extends RecyclerView.ViewHolder {
        private final ViewDiscoverItemBinding mBinding;

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

        public void bindData(int position) {
            if (position >= getItemCount()) {
                return;
            }

            GoodBean item = mList.get(position);
            if (item == null) {
                return;
            }

            if (!TextUtils.isEmpty(item.name)) {
                mBinding.content.setText(item.name);
            }

            mBinding.price.setText(String.format("￥%s", item.price));
            if (!TextUtils.isEmpty(item.image)) {
                Glide.with(mBinding.goodpic.getContext())
                        .load(Url.BASE_URL + item.image)
                        .error(Glide.with(mBinding.goodpic.getContext()).load(R.drawable.find_d))
                        .into(mBinding.goodpic);
            }

            if (!TextUtils.isEmpty(item.detail_url)) {
                mBinding.getRoot().setOnClickListener(v -> {
                    WebViewActivity.newIntent(mContext, item.detail_url, null);
                });
            }
        }
    }
}