package com.getbubblenow.android.fragment;

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

import com.getbubblenow.android.R;
import com.getbubblenow.android.model.Network;

import java.util.List;

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

public class NetworkListRecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {

    public interface ItemClickListener {
        void onItemClick(View view, Network network);
    }

    private final List<Network> networks;
    private final LayoutInflater inflater;
    private final ItemClickListener listener;

    public NetworkListRecyclerViewAdapter(
            final Context context,
            final List<Network> networks,
            final ItemClickListener listener) {
        this.inflater = LayoutInflater.from(context);
        this.networks = networks;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
        final View view = inflater.inflate(R.layout.network_list_item, parent, false);
        return new NetworkListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        final Network network = networks.get(position);
        ((NetworkListViewHolder) holder).myTextViewNickname.setText(network.getNickname());
        ((NetworkListViewHolder) holder).myTextViewNetworkName.setText(network.getName());
        if (network.isRunning()) {
            ((NetworkListViewHolder) holder).myTextViewState.setText(R.string.running);
        } else if (network.isStarting()) {
            ((NetworkListViewHolder) holder).myTextViewState.setText(R.string.starting);
        } else if (network.isRestoring()) {
            ((NetworkListViewHolder) holder).myTextViewState.setText(R.string.restoring);
        }
    }

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


    public class NetworkListViewHolder extends ViewHolder implements View.OnClickListener {

        private final TextView myTextViewNickname;
        private final TextView myTextViewState;
        private final TextView myTextViewNetworkName;

        public NetworkListViewHolder(@NonNull final View itemView) {
            super(itemView);
            myTextViewNickname = itemView.findViewById(R.id.tv_nick_name);
            myTextViewNetworkName = itemView.findViewById(R.id.tv_network_name);
            myTextViewState = itemView.findViewById(R.id.tv_network_state);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(final View view) {
            listener.onItemClick(view, networks.get(getAdapterPosition()));
        }
    }
}
