package com.streamplayer;

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 java.util.List;

public class SectionAdapter extends RecyclerView.Adapter<SectionAdapter.SectionViewHolder> {

    public interface OnSectionSelectedListener {
        void onSectionSelected(int position);
    }

    private final List<String> sections;
    private final OnSectionSelectedListener listener;
    private int selectedIndex = 0;

    public SectionAdapter(List<String> sections, OnSectionSelectedListener listener) {
        this.sections = sections;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull SectionViewHolder holder, int position) {
        holder.title.setText(sections.get(position));
        holder.itemView.setSelected(position == selectedIndex);
        holder.itemView.setOnClickListener(v -> notifySelection(holder));
        holder.itemView.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                notifySelection(holder);
            }
        });
    }

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

    public void setSelectedIndex(int index) {
        if (index < 0 || index >= sections.size()) {
            return;
        }
        if (selectedIndex == index) {
            return;
        }
        int previous = selectedIndex;
        selectedIndex = index;
        notifyItemChanged(previous);
        notifyItemChanged(selectedIndex);
    }

    public int getSelectedIndex() {
        return selectedIndex;
    }

    private void notifySelection(SectionViewHolder holder) {
        int position = holder.getBindingAdapterPosition();
        if (position == RecyclerView.NO_POSITION) {
            return;
        }
        if (listener != null) {
            listener.onSectionSelected(position);
        }
    }

    static class SectionViewHolder extends RecyclerView.ViewHolder {
        final TextView title;

        SectionViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.section_title);
        }
    }
}
