package co.pixelbeard.theanfieldwrap.downloads;

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.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.makeramen.roundedimageview.RoundedImageView;
import com.taishi.library.Indicator;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.Podcast;
import co.pixelbeard.theanfieldwrap.data.RealmPodcast;
import co.pixelbeard.theanfieldwrap.dialog.twoButton.TwoButtonDialogListener;
import co.pixelbeard.theanfieldwrap.playerService.MediaPlayerInterface;
import co.pixelbeard.theanfieldwrap.utils.DateUtils;
import co.pixelbeard.theanfieldwrap.utils.DialogUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.GlideApp;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.SubscriptionUtils;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by Michael Stoddart
 * 01/01/2019.
 */
public class DownloadsAdapter extends RecyclerView.Adapter<DownloadsAdapter.PodcastsViewHolder> {

    private List<RealmPodcast> mPodcasts;
    private OnDownloadedPodcastSelectedListener mListener;
    private MediaPlayerInterface mediaPlayerInterface;


    public DownloadsAdapter(RealmResults<RealmPodcast> podcasts, OnDownloadedPodcastSelectedListener listener, MediaPlayerInterface mediaPlayerInterface) {
        this.mPodcasts = Realm.getDefaultInstance().copyFromRealm(podcasts);
        this.mListener = listener;
        this.mediaPlayerInterface = mediaPlayerInterface;
    }


    @NonNull
    @Override
    public PodcastsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PodcastsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_downloaded_podcast, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull PodcastsViewHolder holder, int position) {

        RealmPodcast realmPodcast = mPodcasts.get(holder.getAdapterPosition());

        Podcast mPodcast = new Podcast(realmPodcast.getPostId(), realmPodcast.getTitle(), realmPodcast.getContent(), realmPodcast.getCreatedDate(),
                realmPodcast.isPremium(), realmPodcast.getFileLocation(), realmPodcast.getThumbnail(), realmPodcast.getMediumImage(),
                realmPodcast.getLargeImage(), realmPodcast.getPodcastLength(), realmPodcast.isPurchased(), realmPodcast.getCost(), realmPodcast.getSubLevel());

        holder.imgDelete.setOnClickListener(v -> DialogUtils.showTwoButtonDialog("Are you sure?", "Are you sure you want to delete:\n" + mPodcast.getTitle(), holder.itemView.getContext(), new TwoButtonDialogListener() {
            @Override
            public void onYesClicked() {
                if (mediaPlayerInterface.isQueued(mPodcast)) {
                    mediaPlayerInterface.stop();
                }
                mListener.deletePodcast(realmPodcast, holder.getAdapterPosition());
            }

            @Override
            public void onNoClicked() {
            }
        }));


        holder.llPodcastMain.setOnClickListener(v -> mListener.onPodcastSelected(mPodcast));

        if (mediaPlayerInterface.isQueued(mPodcast) && mediaPlayerInterface.isPlaying()) {
            holder.musicIndicator.setVisibility(View.VISIBLE);
            holder.imgDelete.setVisibility(View.GONE);
        } else {
            holder.musicIndicator.setVisibility(View.GONE);
            holder.imgDelete.setVisibility(View.VISIBLE);
        }


        holder.txtPodcastTitle.setText(Html.fromHtml(mPodcast.getTitle()));
        GlideApp.with(holder.itemView.getContext()).load(mPodcast.getThumbnail()).placeholder(R.drawable.ic_placeholder_podcast_small).into(holder.imgPodcast);

        if (SubscriptionUtils.userCanAccessAudio(PrefUtils.getInstance().getSubs(), mPodcast)) {
            holder.txtPremium.setVisibility(View.GONE);
        } else {
            holder.txtPremium.setVisibility(View.VISIBLE);
        }


        if (mPodcast.isPurchased()) {
            holder.txtPremium.setVisibility(View.VISIBLE);
            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.txtPodcastDate.setText(DateUtils.getDateddMMYYYY(mPodcast.getCreatedDate()));

        mediaPlayerInterface.getPodcastState(mPodcast.getPostId(), holder.getAdapterPosition(), (podcastState, pos) -> {
            if (podcastState != null && podcastState.isValid()) {
                holder.pbDownloadedPodcastProgress.setVisibility(View.VISIBLE);
                holder.pbDownloadedPodcastProgress.setMax((int) podcastState.getPodcastDuration());
                holder.pbDownloadedPodcastProgress.setProgress((int) podcastState.getPodcastPosition());
            } else {
                holder.pbDownloadedPodcastProgress.setVisibility(View.GONE);
            }
            //TODO stop UI stutter
//            notifyItemChanged(pos);

        });

        try {
            holder.txtPodcastListenTime.setText(String.format(holder.itemView.getContext().getString(R.string.mins_param), mPodcast.getPodcastLength()));
        } catch (Exception e) {
            e.printStackTrace();
            holder.txtPodcastListenTime.setVisibility(View.GONE);
        }
    }

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

    public void remove(int position) {
        if (mPodcasts != null && position < mPodcasts.size() && position >= 0) {
            mPodcasts.remove(position);
            notifyItemRemoved(position);
        }
    }

    public class PodcastsViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.ll_podcast_main)
        LinearLayout llPodcastMain;
        @BindView(R.id.img_podcast)
        RoundedImageView imgPodcast;
        @BindView(R.id.txt_premium)
        TextView txtPremium;
        @BindView(R.id.txt_podcast_date)
        TextView txtPodcastDate;
        @BindView(R.id.txt_podcast_listen_time)
        TextView txtPodcastListenTime;
        @BindView(R.id.txt_podcast_title)
        TextView txtPodcastTitle;
        @BindView(R.id.img_delete)
        ImageView imgDelete;
        @BindView(R.id.music_indicator)
        Indicator musicIndicator;

        @BindView(R.id.pb_downloaded_podcast_progress)
        ProgressBar pbDownloadedPodcastProgress;


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

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


        private void setFonts() {
            txtPremium.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            txtPodcastDate.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            txtPodcastListenTime.setTypeface(FontUtils.getInstance().getDinAlternateBold());
            txtPodcastTitle.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        }
    }
}
