package com.example.lab2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class PhoneListAdapter extends RecyclerView.Adapter<PhoneListAdapter.PhoneViewHolder> {
    public interface OnItemClickListener {
        void onItemClick(Phone phone);
    }

    private List<Phone> phones = new ArrayList<>();
    private OnItemClickListener listener;
    private final LayoutInflater inflater;

    public PhoneListAdapter(Context context) {
        inflater = LayoutInflater.from(context);
    }

    class PhoneViewHolder extends RecyclerView.ViewHolder {
        private final TextView producerView;
        private final TextView modelView;

        public PhoneViewHolder(View itemView) {
            super(itemView);
            producerView = itemView.findViewById(R.id.textProducer);
            modelView = itemView.findViewById(R.id.textModel);

            itemView.setOnClickListener(v -> {
                int position = getAdapterPosition();
                if (listener != null && position != RecyclerView.NO_POSITION) {
                    listener.onItemClick(phones.get(position));
                }
            });
        }

        public void bind(Phone phone) {
            producerView.setText(phone.producer);
            modelView.setText(phone.model);
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    @Override
    public PhoneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.phone_list_item, parent, false);
        return new PhoneViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(PhoneViewHolder holder, int position) {
        Phone current = phones.get(position);
        holder.bind(current);
    }

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

    public void setPhones(List<Phone> phones) {
        this.phones = phones;
        notifyDataSetChanged();
    }

    public Phone getPhoneAt(int position) {
        return phones.get(position);
    }
}
