package com.example.myapplication6;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.button.MaterialButton;
import java.util.ArrayList;
import java.util.List;

public class EntryListAdapter extends RecyclerView.Adapter<EntryListAdapter.Holder> {

    public interface OnEditListener {
        void onEdit(long entryId);
    }

    private final List<bizimdb.Item> items = new ArrayList<>();
    private final OnEditListener editListener;

    public EntryListAdapter(OnEditListener editListener) {
        this.editListener = editListener;
    }

    public void setItems(List<bizimdb.Item> next) {
        items.clear();
        if (next != null) {
            items.addAll(next);
        }
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v =
                LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_collection_entry, parent, false);
        return new Holder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder h, int position) {
        bizimdb.Item it = items.get(position);
        h.emoji.setText(bizimdb.entryEmoji(it.tur));
        h.title.setText(it.baslik != null ? it.baslik : "");
        String type = bizimdb.entryTypeLabel(h.itemView.getContext(), it.tur);
        String meta =
                h.itemView
                        .getContext()
                        .getString(
                                R.string.entry_meta_line,
                                it.tarih != null ? it.tarih : "",
                                it.puan != null ? it.puan : "",
                                type);
        h.meta.setText(meta);
        String notes = it.yorum != null ? it.yorum : "";
        if (notes.isEmpty()) {
            h.notes.setVisibility(View.GONE);
        } else {
            h.notes.setVisibility(View.VISIBLE);
            h.notes.setText(notes);
        }
        h.btnEdit.setOnClickListener(v -> editListener.onEdit(it.id));
    }

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

    static final class Holder extends RecyclerView.ViewHolder {
        final TextView emoji;
        final TextView title;
        final TextView meta;
        final TextView notes;
        final MaterialButton btnEdit;

        Holder(@NonNull View itemView) {
            super(itemView);
            emoji = itemView.findViewById(R.id.textEmoji);
            title = itemView.findViewById(R.id.textTitle);
            meta = itemView.findViewById(R.id.textMeta);
            notes = itemView.findViewById(R.id.textNotes);
            btnEdit = itemView.findViewById(R.id.btnEdit);
        }
    }
}
