package com.unibuy.smartdevice.ui.recycler;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

import com.unibuy.smartdevice.databinding.ActivityProductSearchBinding;
import com.unibuy.smartdevice.databinding.RecyclerSearchTextBinding;

import java.util.List;

public class RecyclerSearchTextAdpter extends RecyclerView.Adapter<RecyclerSearchTextAdpter.ViewHolder> {
    private ActivityProductSearchBinding activityProductSearchBinding;
    private final List<String> textList;

    public RecyclerSearchTextAdpter(ActivityProductSearchBinding activityProductSearchBinding, List<String> textList) {
        this.activityProductSearchBinding = activityProductSearchBinding;
        this.textList = textList;
    }

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

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

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

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String oneText = textList.get(position);
        holder.binding.buttonOneText.setText(oneText);
        holder.binding.buttonOneText.setOnClickListener(new SelectOneTextOnClickListener(activityProductSearchBinding, oneText));
    }

    public class SelectOneTextOnClickListener implements View.OnClickListener {
        private ActivityProductSearchBinding activityProductSearchBinding;
        private String oneText;

        public SelectOneTextOnClickListener(ActivityProductSearchBinding activityProductSearchBinding, String oneText) {
            this.activityProductSearchBinding = activityProductSearchBinding;
            this.oneText = oneText;
        }

        @Override
        public void onClick(View v) {
            String nowText = activityProductSearchBinding.searchProductList.getQuery().toString();
            Log.i("SearchTextOnClick", nowText + oneText);
            activityProductSearchBinding.searchProductList.setQuery(nowText+oneText, false);
        }
    }

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

    public void addProductData(String text) {
        textList.add(text);
        notifyItemInserted(textList.size() -1);
    }
}
