package com.team.app.adapter;

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

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

import com.team.app.R;
import com.team.app.activities.NewsActivity;
import com.team.app.models.News;
import com.github.ybq.android.spinkit.SpinKitView;
import com.squareup.picasso.Picasso;

import java.util.List;

import static com.team.app.Constant.APP_URL_MAIN;

public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public Context context;
    private final List<Object> list;
    private final SpinKitView progress;
    private final OnTopicClickListener onTopicClickListener;
    public interface OnTopicClickListener {
        void onTopicClick();
    }

    public NewsAdapter(Context context2, SpinKitView spinKitView, List<Object> list2,OnTopicClickListener onTopicClickListener) {
        this.context = context2;
        this.progress = spinKitView;
        this.list = list2;
        this.onTopicClickListener = onTopicClickListener;
    }

    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new NewsViewHolder(LayoutInflater.from(this.context).inflate(R.layout.news_list, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        final News news = (News) this.list.get(position);
        NewsViewHolder newsViewHolder = (NewsViewHolder) holder;
        String imgurl = APP_URL_MAIN + "images/";
        Picasso.get().load(imgurl+news.getThumb()).placeholder(R.drawable.logo).fit().into(newsViewHolder.image);
        newsViewHolder.mainDesc.setText(news.getTitle());
        newsViewHolder.desc.setText(news.getDate());
        newsViewHolder.linearLayout.setOnClickListener(view -> {
            NewsActivity.news = news;
            if(onTopicClickListener != null) {
                onTopicClickListener.onTopicClick();
            }
        });
        this.progress.setVisibility(View.GONE);
    }

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

    public static class NewsViewHolder extends RecyclerView.ViewHolder {
        TextView desc;
        ImageView image;
        LinearLayout linearLayout;
        TextView mainDesc;

        NewsViewHolder(View view) {
            super(view);
            this.mainDesc = view.findViewById(R.id.mainDesc);
            this.desc = view.findViewById(R.id.desc);
            this.image = view.findViewById(R.id.image);
            this.linearLayout = view.findViewById(R.id.linearLayout);
        }
    }
}
