package org.torproject.artitoyvpn.ui.logging;

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

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

import org.torproject.artitoyvpn.databinding.LogItemBinding;
import org.torproject.onionmasq.logging.LogItem;

import java.util.LinkedList;


/**
 * {@link RecyclerView.Adapter} that can display a {@link LogItem}.
 */
public class LogRecyclerViewAdapter extends RecyclerView.Adapter<LogRecyclerViewAdapter.ViewHolder> {

    private static final String TAG = LogRecyclerViewAdapter.class.getName();
    private boolean showTimestamps = false;
    private LinkedList<LogItem> logItems;

    public LogRecyclerViewAdapter() {
        logItems = new LinkedList<>();
    }

    public void setShowTimeStamps(boolean show) {
        if (show == this.showTimestamps) {
            return;
        }
        this.showTimestamps = show;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LogItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = logItems.get(position);
        holder.mContentView.setText(holder.mItem.toString(showTimestamps));
    }


    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
    }

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

    public void updateList(LinkedList<LogItem> list) {
        this.logItems = list;
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final TextView mContentView;
        public LogItem mItem;

        public ViewHolder(LogItemBinding binding) {
            super(binding.getRoot());
            mContentView = binding.content;
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}