package com.example.myapplicationnews;

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

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.myapplicationnews.api.model.Article;

import java.util.List;

class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {
    private List<Article> mDataset;
    private LayoutInflater mInflater;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView tvTitle, tvDescription, tvPublishedAt, tvAuthor;
        public ImageView imageView;

        public MyViewHolder(View v) {
            super(v);
            tvTitle = v.findViewById(R.id.item_news_textView_title);
            tvDescription = v.findViewById(R.id.item_news_textView_description);
            tvPublishedAt = v.findViewById(R.id.item_news_textView_publishedAt);
            tvAuthor = v.findViewById(R.id.item_news_textView_author);

            imageView = v.findViewById(R.id.item_news_imageView_image);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public NewsAdapter(Context context, List<Article> myDataset) {
        mInflater = LayoutInflater.from(context);
        mDataset = myDataset;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = mInflater.inflate(R.layout.item_news, parent, false);

        return new MyViewHolder(v);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.tvTitle.setText(mDataset.get(position).getTitle());
        holder.tvDescription.setText(mDataset.get(position).getDescription());
        holder.tvPublishedAt.setText(mDataset.get(position).getPublishedAt());
        holder.tvAuthor.setText(mDataset.get(position).getAuthor());

        Glide.with(holder.imageView).load(mDataset.get(position).getUrlToImage()).into(holder.imageView);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        if (mDataset == null) return 0;
        return mDataset.size();
    }
}
