package com.unibuy.smartdevice.ui.recycler;

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

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

import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.databinding.RecyclerProductListBinding;
import com.unibuy.smartdevice.ui.tools.ImageGlide;

import java.util.List;

public class RecyclerProductListAdpter extends RecyclerView.Adapter<RecyclerProductListAdpter.ViewHolder> {
    private Logs logs;
    private Context context;
    private final List<ProductStructure> ProductList;

    public RecyclerProductListAdpter(Context context, List<ProductStructure> productList) {
        this.logs = new Logs(this.getClass());
        this.context = context;
        this.ProductList = productList;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        RecyclerProductListBinding binding;

        public ViewHolder(@NonNull RecyclerProductListBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 使用 ViewBinding 來綁定佈局
        RecyclerProductListBinding binding = RecyclerProductListBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ProductStructure product = ProductList.get(position);

        String urlString = product.getProductImg();
        try {
            new ImageGlide(context).fileload(urlString, holder.binding.imageProductPicture);
        } catch (LogsEmptyException e) {
            this.logs.warning(e);
        }

        holder.binding.textProductId.setText(product.getProductID());
        holder.binding.textProductName.setText(product.getProductName());
        holder.binding.textPrice.setText(String.valueOf(product.getMachinePrice() > 0? product.getMachinePrice(): product.getSellingPrice()));
    }

    @Override
    public int getItemCount() {
        return ProductList.size();
    }

    public void addProductData(ProductStructure productStructure) {
        ProductList.add(productStructure);
        notifyItemInserted(ProductList.size() -1);
    }
}
