package co.pixelbeard.theanfieldwrap.writing;

import android.content.Context;
import android.text.Html;
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.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.Article;
import co.pixelbeard.theanfieldwrap.databinding.ItemLoadingBinding;
import co.pixelbeard.theanfieldwrap.loading.LoadingViewHolder;
import co.pixelbeard.theanfieldwrap.utils.DateUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.GlideApp;
import co.pixelbeard.theanfieldwrap.utils.TextUtils;

/**
 * Created by Michael Stoddart
 * 07/01/2019.
 */
public class WritingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<Article> mArticles;
    private Article mFeaturedArticle;
    private ArticleSelectedListener mListener;


    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;
    private boolean isRefreshing;


    public WritingAdapter(List<Article> articles, Article featuredArticle, ArticleSelectedListener listener) {

        this.mArticles = articles;
        this.mFeaturedArticle = featuredArticle;
        this.mListener = listener;
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        if (viewType == VIEW_TYPE_LOADING) {
            return new LoadingViewHolder(ItemLoadingBinding.inflate(inflater, parent, false));
        } else {
            return new WritingViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_writing, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {

        if (viewHolder instanceof LoadingViewHolder) {
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) viewHolder;
            loadingViewHolder.binding.txtLoadingMore.setText(viewHolder.itemView.getContext().getString(R.string.loading_more_articles));
        } else {
            WritingViewHolder holder = (WritingViewHolder) viewHolder;
            Article article = mArticles.get(holder.getAdapterPosition());
            if (holder.getAdapterPosition() == 0 && mFeaturedArticle != null) {
                setFeaturedArticle(mFeaturedArticle, holder);
                holder.clFeaturedArticle.setVisibility(View.VISIBLE);
            } else {
                holder.clFeaturedArticle.setVisibility(View.GONE);
            }

            setImage(article, holder.itemView.getContext(), holder.imgWriting);

            holder.llWritingMain.setOnClickListener(v -> mListener.onArticleSelected(article));
            holder.txtWritingTitle.setText(Html.fromHtml(article.getTitle()));

            holder.txtWritingDate.setText(DateUtils.getDateddMMYYYY(article.getCreatedDate()));
        }
    }

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

    @Override
    public int getItemViewType(int position) {
        return mArticles.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
    }

    public void add(List<Article> articles) {
        removeLoader();

        int oldSize = mArticles.size();
        if (articles != null) {
            mArticles.addAll(articles);
            notifyItemRangeInserted(oldSize, articles.size());
        }
    }

    private void removeLoader() {
        try {
            for (int i = 0; i < mArticles.size(); i++) {
                Article article = mArticles.get(i);
                if (article == null) {
                    mArticles.remove(i);
                    notifyItemRemoved(i);
                    i = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            FirebaseCrashlytics.getInstance().recordException(e);
        }
        isRefreshing = false;
    }

    public void addLoader() {
        mArticles.add(null);
        isRefreshing = true;
        notifyItemInserted(mArticles.size() - 1);
    }

    public boolean isRefreshing() {
        return isRefreshing;
    }

    private void setFeaturedArticle(Article article, WritingViewHolder holder) {

        GlideApp.with(holder.itemView.getContext()).load(article.getLargeImage()).placeholder(R.drawable.ic_placeholder_writing_large).into(holder.imgFeaturedArticle);

        TextUtils.setTextPaddingColor(holder.txtFeaturedArticleName, Html.fromHtml(article.getTitle()).toString(), holder.itemView.getContext());

        holder.clFeaturedArticle.setOnClickListener(v -> mListener.onArticleSelected(article));
        holder.txtFeaturedArticleDate.setText(DateUtils.getDateddMMYYYY(article.getCreatedDate()));
    }

    private void setImage(Article mArticle, Context context, RoundedImageView imageView) {
        String imageUrl = "";

        if (mArticle != null) {
            if (mArticle.getThumbnail() != null && !mArticle.getThumbnail().equals("")) {
                imageUrl = mArticle.getThumbnail();
            } else if (mArticle.getMediumImage() != null && !mArticle.getMediumImage().equals("")) {
                imageUrl = mArticle.getMediumImage();
            } else if (mArticle.getLargeImage() != null && !mArticle.getLargeImage().equals("")) {
                imageUrl = mArticle.getLargeImage();
            }
        }

        if (imageUrl.equals("")) {
            imageView.setImageResource(R.drawable.ic_placeholder_writing_small);
        } else {
            GlideApp.with(context)
                    .load(imageUrl)
                    .placeholder(R.drawable.ic_placeholder_writing_small)
                    .into(imageView);
        }
    }

    public class WritingViewHolder extends RecyclerView.ViewHolder {


        @BindView(R.id.cl_featured_article)
        ConstraintLayout clFeaturedArticle;
        @BindView(R.id.txt_featured_article_date)
        TextView txtFeaturedArticleDate;
        @BindView(R.id.img_featured_article)
        ImageView imgFeaturedArticle;
        @BindView(R.id.txt_featured_article_name)
        TextView txtFeaturedArticleName;


        @BindView(R.id.img_writing)
        RoundedImageView imgWriting;
        @BindView(R.id.txt_writing_date)
        TextView txtWritingDate;
        @BindView(R.id.txt_writing_title)
        TextView txtWritingTitle;
        @BindView(R.id.ll_writing_main)
        LinearLayout llWritingMain;


        public WritingViewHolder(@NonNull View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);
            setFonts();
        }

        private void setFonts() {
            txtWritingTitle.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            txtWritingDate.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            txtFeaturedArticleName.setTypeface(FontUtils.getInstance().getRobotoBold());
            txtFeaturedArticleDate.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        }
    }

}
