package co.pixelbeard.theanfieldwrap.videos;

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

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
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.Video;
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.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.SubscriptionUtils;

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

    private List<Video> mVideos;
    private OnVideoSelectedListener mListener;

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

    public VideosAdapter(List<Video> videos, OnVideoSelectedListener listener) {
        this.mVideos = videos;
        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 VideosViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_video, 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_videos));


        } else {

            VideosViewHolder holder = (VideosViewHolder) viewHolder;
            Video mVideo = mVideos.get(holder.getAdapterPosition());

            setImage(mVideo, holder.itemView.getContext(), holder.imgVideoThumb);
            holder.txtVideoTitle.setText(Html.fromHtml(mVideo.getTitle()));
            holder.txtVideoDate.setText(DateUtils.getDateddMMYYYY(mVideo.getCreatedDate()));

            if (SubscriptionUtils.userCanAccessVideo(PrefUtils.getInstance().getSubs())) {
                holder.txtPremium.setVisibility(View.GONE);
            } else if (mVideo.getCost() == 0) {
                holder.txtPremium.setVisibility(View.GONE);
            } else {
                holder.txtPremium.setVisibility(View.VISIBLE);
            }

            if (mVideo.isPurchased()) {
                holder.txtPremium.setText(holder.itemView.getContext().getString(R.string.purchased));
                holder.txtPremium.setBackgroundColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.grey9b9b9b));
            } else {
                holder.txtPremium.setText(holder.itemView.getContext().getString(R.string.premium));
                holder.txtPremium.setBackgroundColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.black1B1B1B));
            }

            holder.itemView.setOnClickListener(v -> mListener.onVideoSelected(mVideo));
        }
    }

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

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

    public void add(List<Video> videos) {
        removeLoader();

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

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

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

    public boolean isRefreshing() {
        return isRefreshing;
    }


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


        if (mVideo != null) {

            if (imageIsAvailable(mVideo.getLargeImage())) {
                imageUrl = mVideo.getLargeImage();
            } else if (imageIsAvailable(mVideo.getMediumImage())) {
                imageUrl = mVideo.getMediumImage();
            } else if (imageIsAvailable(mVideo.getThumbnail())) {
                imageUrl = mVideo.getThumbnail();
            }
        }

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

    }

    private boolean imageIsAvailable(String url) {
        return url != null && !url.equals("");
    }

    public class VideosViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.img_video_thumb)
        RoundedImageView imgVideoThumb;
        @BindView(R.id.txt_premium)
        TextView txtPremium;
        @BindView(R.id.txt_video_title)
        TextView txtVideoTitle;
        @BindView(R.id.txt_video_date)
        TextView txtVideoDate;


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

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

        private void setFonts() {
            txtPremium.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            txtVideoTitle.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            txtVideoDate.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        }
    }

}
