package com.streamplayer;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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

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

public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder> {

    public interface OnChannelClickListener {
        void onChannelClick(StreamChannel channel);
    }

    private final List<StreamChannel> channels = new ArrayList<>();
    private final OnChannelClickListener listener;

    public ChannelAdapter(OnChannelClickListener listener) {
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ChannelViewHolder holder, int position) {
        StreamChannel channel = channels.get(position);
        holder.name.setText(channel.getName());
        holder.icon.setImageResource(R.drawable.ic_channel_default);
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onChannelClick(channel);
            }
        });
        holder.itemView.setOnFocusChangeListener((v, hasFocus) -> {
            float scale = hasFocus ? 1.08f : 1f;
            v.animate().scaleX(scale).scaleY(scale).setDuration(120).start();
            v.setSelected(hasFocus);
        });
    }

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

    static class ChannelViewHolder extends RecyclerView.ViewHolder {
        final ImageView icon;
        final TextView name;

        ChannelViewHolder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.channel_icon);
            name = itemView.findViewById(R.id.channel_name);
        }
    }

    public void submitList(List<StreamChannel> newChannels) {
        channels.clear();
        if (newChannels != null) {
            channels.addAll(newChannels);
        }
        notifyDataSetChanged();
    }
}
