package co.pixelbeard.theanfieldwrap.podcastDetails;


import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.Error;
import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchListener;
import com.tonyodev.fetch2.Status;
import com.tonyodev.fetch2core.DownloadBlock;

import org.jetbrains.annotations.NotNull;
import org.parceler.Parcels;

import java.util.List;
import java.util.Locale;

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.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.data.source.local.LocalRepository;
import co.pixelbeard.theanfieldwrap.data.source.remote.RemoteRepository;
import co.pixelbeard.theanfieldwrap.dialog.twoButton.TwoButtonDialogListener;
import co.pixelbeard.theanfieldwrap.dialog.unlockEpisodes.UnlockEpisodeDialog;
import co.pixelbeard.theanfieldwrap.dialog.unlockEpisodes.UnlockEpisodeListener;
import co.pixelbeard.theanfieldwrap.downloader.DownloadConstants;
import co.pixelbeard.theanfieldwrap.home.HomeFragmentListener;
import co.pixelbeard.theanfieldwrap.playerService.MediaConstants;
import co.pixelbeard.theanfieldwrap.playerService.MediaPlayerInterface;
import co.pixelbeard.theanfieldwrap.playerService.PodcastStorageUtil;
import co.pixelbeard.theanfieldwrap.utils.AnalyticsConstants;
import co.pixelbeard.theanfieldwrap.utils.AnimUtils;
import co.pixelbeard.theanfieldwrap.utils.BaseFragment;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
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.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.ScreenUtils;
import co.pixelbeard.theanfieldwrap.utils.SubscriptionUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import io.realm.Realm;
import rx.Observer;

public class PodcastDetailsFragment extends BaseFragment implements PodcastDetailsContract.View, FetchListener {

    private static final String TAG = PodcastDetailsFragment.class.getSimpleName();

    //Toolbar
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.img_download)
    ImageView imgDownload;
    @BindView(R.id.pb_download_progress)
    ProgressBar pbDownloadProgress;
    @BindView(R.id.txt_download_progress)
    TextView txtDownloadProgress;
    @BindView(R.id.rl_download_container)
    RelativeLayout rlDownloadContainer;

    //Token Balance
    @BindView(R.id.cl_token_balance)
    ConstraintLayout clTokenBalance;
    @BindView(R.id.txt_your_balance_header)
    TextView txtYourBalanceHeader;
    @BindView(R.id.txt_token_balance)
    TextView txtTokenBalance;


    //Hero image
    @BindView(R.id.cl_podcast_main_image)
    ConstraintLayout clPodcastMainImage;
    @BindView(R.id.img_podcast_main_image)
    ImageView imgPodcastMainImage;


    //Play container
    @BindView(R.id.ll_play_pause_container)
    LinearLayout llPlayPauseContainer;
    @BindView(R.id.img_play_podcast)
    ImageView imgPlayPausePodcast;
    @BindView(R.id.txt_preview)
    TextView txtPreview;

    //Premium Container
    @BindView(R.id.ll_premium_container)
    LinearLayout llPremiumContainer;
    @BindView(R.id.img_locked)
    ImageView imgLocked;
    @BindView(R.id.txt_premium)
    TextView txtPremium;

    //Progress bar
    @BindView(R.id.ll_progress_bar_container)
    LinearLayout llProgressBarContainer;
    @BindView(R.id.pb_podcast_progress)
    ProgressBar pbPodcastProgress;


    //Unlock episode
    @BindView(R.id.cl_unlock_episode_container)
    ConstraintLayout clUnlockEpisodeContainer;
    @BindView(R.id.txt_unlock_episode)
    TextView txtUnlockEpisodeTitle;

    @BindView(R.id.btn_how_to_subscribe)
    Button btnHowToSubscribe;
    @BindView(R.id.btn_sign_up)
    Button btnSignUp;
    @BindView(R.id.btn_login)
    Button btnLogin;

    @BindView(R.id.ll_login_sign_up_container)
    LinearLayout llLoginSignUpContainer;
    @BindView(R.id.ll_buy_episode)
    LinearLayout llBuyEpisode;
    @BindView(R.id.txt_podcast_cost)
    TextView txtPodcastCost;


    //Rest of UI
    @BindView(R.id.ll_podcast_date_container)
    LinearLayout llPodcastDateContainer;
    @BindView(R.id.txt_podcast_title)
    TextView txtPodcastTitle;
    @BindView(R.id.txt_podcast_date)
    TextView txtPodcastDate;
    @BindView(R.id.txt_podcast_listen_time)
    TextView txtPodcastListenTime;
    @BindView(R.id.txt_podcast_details)
    TextView txtPodcastDetails;

    private UnlockEpisodeDialog unlockEpisodeDialog;

    private HomeFragmentListener mListener;
    private MediaPlayerInterface mediaPlayerInterface;
    private Context mContext;

    private static final String PODCAST = "PODCAST";
    private static final String PODCAST_ID = "PODCAST_ID";
    private Podcast mPodcast;
    private Long mPodcastId;

    private PodcastDetailsContract.Presenter mPresenter;

    private boolean wasPlayed = false, isPreview = false;

    private Observer<String> serviceObserver;
    private boolean downloadErrorShowing = false;

    private boolean shouldCallOnResume = false;


    public PodcastDetailsFragment() {
        // Required empty public constructor
    }

    public static PodcastDetailsFragment newInstance(Podcast podcast) {
        PodcastDetailsFragment fragment = new PodcastDetailsFragment();
        Bundle args = new Bundle();
        args.putParcelable(PODCAST, Parcels.wrap(podcast));
        fragment.setArguments(args);
        return fragment;
    }

    public static PodcastDetailsFragment newInstance(Long podcastId) {
        PodcastDetailsFragment fragment = new PodcastDetailsFragment();
        Bundle args = new Bundle();
        args.putLong(PODCAST_ID, podcastId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mContext = context;
        mListener = (HomeFragmentListener) context;
        mediaPlayerInterface = (MediaPlayerInterface) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPodcast = Parcels.unwrap(getArguments().getParcelable(PODCAST));
            mPodcastId = getArguments().getLong(PODCAST_ID);
        }

        new PodcastDetailsPresenter(this, new DataRepository(new LocalRepository(Realm.getDefaultInstance()), new RemoteRepository()));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_podcast_details, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setTextViewFont();
        setClickListeners();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        TawController.setCurrentPage(TAG);

        if (isAdded()) {
            txtTokenBalance.setText(String.format(getString(R.string.tokens_argument), PrefUtils.getInstance().getIntPref(PrefKey.TOKEN_BALANCE)));
        }

        if (mPodcast != null) {
            setPodcast(mPodcast);
        } else {
            mPresenter.getPodcastByIdRemote(mPodcastId);
        }
        mPresenter.checkWalletBalance();
    }

    @Override
    public void onPause() {
        super.onPause();
        Fetch.Impl.getDefaultInstance().removeListener(this);
        if (isPreview) {
            mPodcast.setPlaying(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        serviceObserver = null;
    }

    private void setTextViewFont() {
        txtPremium.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtPodcastTitle.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtPodcastDate.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtPodcastListenTime.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtPodcastDetails.setTypeface(FontUtils.getInstance().getArialReg());
        txtPreview.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtUnlockEpisodeTitle.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtPodcastCost.setTypeface(FontUtils.getInstance().getDinAlternateBold());


        btnSignUp.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        btnLogin.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        btnHowToSubscribe.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtDownloadProgress.setTypeface(FontUtils.getInstance().getDinAlternateBold());

        txtYourBalanceHeader.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtTokenBalance.setTypeface(FontUtils.getInstance().getDinAlternateBold());

    }

    private void setClickListeners() {
        llBack.setOnClickListener(v -> mListener.goBack());

        btnSignUp.setOnClickListener(v -> {
            mListener.startSignUpActivityAsGuest();
        });

        btnLogin.setOnClickListener(v -> mListener.startLoginActivityAsGuest());

        btnHowToSubscribe.setOnClickListener(v -> {
            mListener.setHowToSubscribeFrag(true);
        });

        imgDownload.setOnClickListener(v -> {
            imgDownload.setVisibility(View.GONE);
            pbDownloadProgress.setVisibility(View.VISIBLE);
            mPresenter.downloadPodcast(mPodcast, mContext);
        });

        imgPlayPausePodcast.setOnClickListener(v -> {
            imgPlayPausePodcast.setEnabled(false);

            if (mediaPlayerInterface.isQueued(mPodcast)) {
                if (mediaPlayerInterface.isPlaying()) {
                    imgPlayPausePodcast.setImageResource(R.drawable.ic_play_red);
                    mediaPlayerInterface.pause();
                    mPodcast.setPlaying(false);
                } else {
                    imgPlayPausePodcast.setImageResource(R.drawable.ic_pause_red);
                    mediaPlayerInterface.play(mPodcast, ((BitmapDrawable) imgPodcastMainImage.getDrawable()).getBitmap());
                    if (!isPreview) {
                        mPodcast.setPlaying(true);
                    }
                }
            } else {
                if (mediaPlayerInterface.isPlaying()) {
                    mediaPlayerInterface.pause();
                    mPodcast.setPlaying(false);
                }
                imgPlayPausePodcast.setImageResource(R.drawable.ic_pause_red);
                mListener.showAudioPlayerOverlay(mPodcast, true);
                shouldCallOnResume = true;
                mListener.hideMiniPlayer();

                new Thread(() -> {
                    while (!mediaPlayerInterface.isServiceBound()) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    mediaPlayerInterface.subscribeToPlayerService(getServiceObserver());
                }).start();
            }
            new Handler().postDelayed(() -> {
                imgPlayPausePodcast.setEnabled(true);
                wasPlayed = true;
            }, 1200);

        });

        llBuyEpisode.setOnClickListener(v -> DialogUtils.showTwoButtonDialog("Are you sure?",
                "Are you sure you want to purchase the podcast " + mPodcast.getTitle() + "?", mContext, new TwoButtonDialogListener() {
                    @Override
                    public void onYesClicked() {
                        mPresenter.purchaseItem(String.valueOf(mPodcast.getPostId()));
                    }

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

        clTokenBalance.setOnClickListener(v -> mListener.setWalletFrag());
    }

    private void setData() {

        setIsPreview();
        setPodcastData();

        if (mediaPlayerInterface.isServiceBound()) {
            mediaPlayerInterface.subscribeToPlayerService(getServiceObserver());
        }

        if (mediaPlayerInterface.isQueued(mPodcast)) {
            if (mediaPlayerInterface.isPlaying()) {
                imgPlayPausePodcast.setImageResource(R.drawable.ic_pause_red);
            } else {
                imgPlayPausePodcast.setImageResource(R.drawable.ic_play_red);
            }
        } else {
            imgPlayPausePodcast.setImageResource(R.drawable.ic_play_red);
        }

        if (PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
            setGuestAccountUI();
        } else if (SubscriptionUtils.userCanAccessAudio(PrefUtils.getInstance().getSubs(), mPodcast)) {
            setHasSubsUI();
        } else {
            setNoSubsUI();
        }
    }


    private void setIsPreview() {
        if (PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
            isPreview = true;
        } else {
            isPreview = !SubscriptionUtils.userCanAccessAudio(PrefUtils.getInstance().getSubs(), mPodcast);
        }
    }

    private void setPodcastData() {
        GlideApp.with(mContext)
                .load(mPodcast.getLargeImage())
                .placeholder(R.drawable.ic_placeholder_podcast_large)
                .into(imgPodcastMainImage);

        txtPodcastTitle.setText(Html.fromHtml(mPodcast.getTitle()));

        String content = mPodcast.getContent();
        content = content.replaceAll("\\n", "<br>");

        txtPodcastDetails.setText(Html.fromHtml(content));
        txtPodcastDate.setText(DateUtils.getDateddMMYYYY(mPodcast.getCreatedDate()));


        if (mPodcast.isPremium()) {
            txtPodcastCost.setText(String.format(getString(R.string.tokens_argument), mPodcast.getCost()));
        }
        try {
            txtPodcastListenTime.setText(String.format(getString(R.string.mins_param), mPodcast.getPodcastLength()));
        } catch (Exception e) {
            e.printStackTrace();
            txtPodcastListenTime.setVisibility(View.GONE);
        }

    }

    private void checkForDownload() {
        RealmPodcast realmPodcast = mPresenter.getPodcastByIdLocal(mPodcast.getPostId());
        if (realmPodcast != null) {
            rlDownloadContainer.setVisibility(View.GONE);
            mPodcast.setFileLocation(realmPodcast.getFileLocation());
        } else {
            rlDownloadContainer.setVisibility(View.VISIBLE);
            mPodcast.setFileLocation(null);
        }
    }

    private void showUi() {

        if (isAdded()) {

            if (!SubscriptionUtils.userCanAccessAudio(PrefUtils.getInstance().getSubs(), mPodcast) || PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
                if (mPodcast.isPremium() || PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
                    new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(clUnlockEpisodeContainer, ScreenUtils.dpToPx(50, mContext), 0, null), 500);
                }
            }

//        if (!PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
            new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(llPlayPauseContainer, ScreenUtils.dpToPx(50, mContext), 0, null), 200);
//        }

            new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(clPodcastMainImage, ScreenUtils.dpToPx(50, mContext), 0, null), 100);

            if (!PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
                if (llPremiumContainer.getVisibility() != View.GONE) {
                    new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(llPremiumContainer, ScreenUtils.dpToPx(50, mContext), 0, null), 200);
                }
            } else if (PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT) && mPodcast.isPremium()) {
                new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(llPremiumContainer, ScreenUtils.dpToPx(50, mContext), 0, null), 200);
            } else {
                llPremiumContainer.setVisibility(View.GONE);
            }

            mediaPlayerInterface.getPodcastState(mPodcast.getPostId(), 0, (podcastState, position) -> {

                if (podcastState != null && podcastState.isValid() && SubscriptionUtils.userCanAccessAudio(PrefUtils.getInstance().getSubs(), mPodcast)) {
                    new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(llProgressBarContainer, ScreenUtils.dpToPx(50, mContext), 0, null), 500);
                    pbPodcastProgress.setMax((int) podcastState.getPodcastDuration());
                    pbPodcastProgress.setProgress((int) podcastState.getPodcastPosition());
                } else if (!mPodcast.isPremium() || SubscriptionUtils.userCanAccessAudio(PrefUtils.getInstance().getSubs(), mPodcast)) {
                    new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(llProgressBarContainer, ScreenUtils.dpToPx(50, mContext), 0, null), 500);
                    pbPodcastProgress.setMax(100);
                    pbPodcastProgress.setProgress(0);
                } else {
                    llProgressBarContainer.setVisibility(View.GONE);
                }
            });

            new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(txtPodcastTitle, ScreenUtils.dpToPx(50, mContext), 0, null), 300);
            new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(llPodcastDateContainer, ScreenUtils.dpToPx(50, mContext), 0, null), 400);
            new Handler().postDelayed(() -> AnimUtils.startTranslateAlphaEntryAnimationSet(txtPodcastDetails, ScreenUtils.dpToPx(50, mContext), 0, null), 600);
        }
    }

    private void setGuestAccountUI() {
        clTokenBalance.setVisibility(View.GONE);
        txtPreview.setVisibility(View.VISIBLE);
        btnHowToSubscribe.setVisibility(View.GONE);
        rlDownloadContainer.setVisibility(View.GONE);

        llLoginSignUpContainer.setVisibility(View.VISIBLE);
        llBuyEpisode.setVisibility(View.GONE);

        if (!mPodcast.isPremium()) {
            llPremiumContainer.setVisibility(View.GONE);
        }


    }

    private void setNoSubsUI() {
        clTokenBalance.setVisibility(View.VISIBLE);

        llBuyEpisode.setVisibility(View.VISIBLE);
        btnHowToSubscribe.setVisibility(View.VISIBLE);
        llLoginSignUpContainer.setVisibility(View.GONE);
        // Check if purchased
        if (mPodcast.isPurchased()) {
            setHasSubsUI();
            txtPremium.setText(getString(R.string.purchased));
        } else {
            if (!mPodcast.isPremium()) {
                llPremiumContainer.setVisibility(View.GONE);
            }
            txtPreview.setVisibility(View.VISIBLE);
            rlDownloadContainer.setVisibility(View.GONE);
        }
    }

    private void setHasSubsUI() {
        clTokenBalance.setVisibility(View.VISIBLE);
        imgLocked.setVisibility(View.GONE);
        clUnlockEpisodeContainer.setVisibility(View.GONE);

        if (SubscriptionUtils.userCanAccessAudio(PrefUtils.getInstance().getSubs(), mPodcast)) {
            if (mPodcast.getSubLevel() == 0 && !mPodcast.isPremium()) {
                llPremiumContainer.setVisibility(View.GONE);
            } else {
                if (mPodcast.isPurchased()) {
                    txtPremium.setText(getString(R.string.purchased));
                } else {
                    txtPremium.setText(getString(R.string.subscribed));
                }
                txtPremium.setBackgroundColor(ContextCompat.getColor(mContext, R.color.grey9b9b9b));
            }
        } else {
            llPremiumContainer.setVisibility(View.GONE);
        }
        txtPreview.setVisibility(View.GONE);
        checkForDownload();
    }

    private Observer<String> getServiceObserver() {
        if (serviceObserver != null) {
            return serviceObserver;
        }

        serviceObserver = new Observer<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {

                Podcast storedPodcast = PodcastStorageUtil.getInstance().loadAudio();


                switch (s) {
                    case MediaConstants.RX_PLAY:
                        Log.d("RX", "RX_PLAY");
                        if (storedPodcast.getPostId().equals(mPodcast.getPostId())) {
                            imgPlayPausePodcast.setImageResource(R.drawable.ic_pause_red);
                            mPodcast.setPlaying(true);
                        }
                        break;
                    case MediaConstants.RX_PAUSE:
                        Log.d("RX", "RX_PAUSE");
                        imgPlayPausePodcast.setImageResource(R.drawable.ic_play_red);
                        mPodcast.setPlaying(false);
                        break;
                    case MediaConstants.RX_COMPLETE:
                        Log.d("RX", "RX_COMPLETE ");
                        imgPlayPausePodcast.setImageResource(R.drawable.ic_play_red);
                        mPodcast.setPlaying(false);
                        break;
                    case MediaConstants.RX_STOP:
                        Log.d("DEETS RX", "RX_STOP");
                        imgPlayPausePodcast.setImageResource(R.drawable.ic_play_red);
                        mPodcast.setPlaying(false);
                        Log.d("WAS PLAYED", "" + wasPlayed);
                        Log.d("IS PREVIEW", "" + isPreview);

                        if (wasPlayed && isPreview) {//&& mediaPlayerInterface.isQueued(mPodcast)) {
                            new Handler().postDelayed(() -> {
                                if (isAdded() && !isDetached() && unlockEpisodeDialog == null) {
                                    unlockEpisodeDialog = new UnlockEpisodeDialog(mContext, new UnlockEpisodeListener() {
                                        @Override
                                        public void purchasePodcastClicked() {
                                            llBuyEpisode.performClick();
                                        }

                                        @Override
                                        public void createAccountClicked() {
                                            btnSignUp.performClick();
                                        }

                                        @Override
                                        public void howToSubscribeClicked() {
                                            mListener.setHowToSubscribeFrag(true);
                                        }
                                    }, mPodcast);
                                    unlockEpisodeDialog.setOnDismissListener(dialog1 -> {
                                        wasPlayed = false;
                                        unlockEpisodeDialog = null;
                                    });
                                    if (unlockEpisodeDialog != null && !unlockEpisodeDialog.isShowing()) {
                                        unlockEpisodeDialog.show();
                                    }
                                }
                            }, 600);
                        }
                        PodcastStorageUtil.getInstance().clearStoredPodcast();
                        break;
                }
            }
        };

        return serviceObserver;
    }

    @Override
    public void setPresenter(PodcastDetailsContract.Presenter presenter) {
        if (presenter != null) {
            this.mPresenter = presenter;
        } else {
            throw new RuntimeException("Presenter is null");
        }
    }

    @Override
    public void goBack() {
        mListener.goBack();
    }

    @Override
    public void showLoader(String text) {
        if (mListener != null && isAdded()) {
            mListener.showLoader(text);
        }
    }

    @Override
    public void hideLoader() {
        new Handler().postDelayed(() -> {
            if (mListener != null && isAdded()) {
                mListener.hideLoader();
            }
        }, 300);
    }

    @Override
    public void onUnknownError(String error) {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.error), error, null);
        }
    }

    @Override
    public void onTimeout() {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.timeout_title), getString(R.string.timeout_body), null);
        }
    }

    @Override
    public void onNetworkError() {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.network_error_title), getString(R.string.network_error_body), null);
        }
    }

    @Override
    public void onConnectionError() {
        if (mListener != null && isAdded()) {
            mListener.showNoInternetHeader();
        }
    }

    @Override
    public void logoutUser() {
        mPresenter.clearUserData(mContext);

        if (mediaPlayerInterface.isPlaying()) {
            mediaPlayerInterface.stop();
        }
        PodcastStorageUtil.getInstance().clearStoredPodcast();
        mListener.startWalkThroughActivity();
    }

    @Override
    public boolean checkConnection() {
        return ConnectionUtils.userHasConnection(mContext);
    }

    @Override
    public void updateUI(Download download) {

        if (isAdded()) {
            if (download != null && download.getUrl().equals(mPodcast.getPodcastFullUrl())) {
                if (download.getProgress() < 100) {
                    pbDownloadProgress.setVisibility(View.VISIBLE);

                    ObjectAnimator.ofInt(pbDownloadProgress, "progress", download.getProgress())
                            .setDuration(300)
                            .start();

//                    pbDownloadProgress.setProgress(download.getProgress());
                    txtDownloadProgress.setVisibility(View.VISIBLE);
                    imgDownload.setVisibility(View.GONE);
                    rlDownloadContainer.setVisibility(View.VISIBLE);
                    if (download.getProgress() < 0) {
                        txtDownloadProgress.setText(String.format(Locale.getDefault(), "%d%%", 0));
                    } else {
                        txtDownloadProgress.setText(String.format(Locale.getDefault(), "%d%%", download.getProgress()));
                    }
                } else {
                    pbDownloadProgress.setVisibility(View.GONE);
                    txtDownloadProgress.setVisibility(View.GONE);
                    if (mPresenter.getPodcastByIdLocal(mPodcast.getPostId()) != null) {
                        rlDownloadContainer.setVisibility(View.GONE);
                    } else {
                        rlDownloadContainer.setVisibility(View.VISIBLE);
                        imgDownload.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    }

    @Override
    public void setPodcast(Podcast podcast) {
        if (podcast != null) {
            this.mPodcast = podcast;
            mPresenter.recordAnalytic(AnalyticsConstants.VIEWED_PODCAST, String.valueOf(mPodcast.getPostId()), "1");
            if (isAdded()) {
                setData();
                Fetch.Impl.getDefaultInstance().addListener(this, true);
                new Handler().postDelayed(this::showUi, 100);
            }
        }
    }

    @Override
    public void setPodcastPurchased(boolean isPurchased) {
        mPodcast.setPurchased(isPurchased);
        if (isAdded()) {
            setData();
            Fetch.Impl.getDefaultInstance().addListener(this, true);
            new Handler().postDelayed(this::showUi, 100);
        }
    }

    @Override
    public void showErrorDialog(String message) {
        if (isAdded()) {
            DialogUtils.showSingleButtonDialog(getString(R.string.oops), message, mContext, null);
        }
    }

    @Override
    public void showBalanceTooLowDialog() {
        if (isAdded()) {
            DialogUtils.showTwoButtonDialog(getString(R.string.not_enough_tokens), getString(R.string.balance_too_low_explanation), mContext, new TwoButtonDialogListener() {
                @Override
                public void onYesClicked() {
                    mListener.setBuyTokensFragment();
                }

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

    @Override
    public void updateWalletBalance(int balance) {
        if (isAdded()) {
            txtTokenBalance.setText(String.format(getString(R.string.tokens_argument), balance));
        }
    }


    public void becameVisible() {
//        if (shouldCallOnResume) {
//            onResume();
//            shouldCallOnResume = false;
//        }
    }

    /**
     * FetchListener Callbacks
     */

    @Override
    public void onAdded(@NotNull Download download) {
        updateUI(download);
    }

    @Override
    public void onQueued(@NotNull Download download, boolean b) {
        updateUI(download);
    }

    @Override
    public void onWaitingNetwork(@NotNull Download download) {
        updateUI(download);
    }

    @Override
    public void onCompleted(@NotNull Download download) {
        mPresenter.savePodcast(mPodcast, download);
        new Handler().postDelayed(() -> updateUI(download), 50);
    }

    @Override
    public void onError(@NotNull Download download, @NotNull Error error, @org.jetbrains.annotations.Nullable Throwable throwable) {
        Fetch.Impl.getDefaultInstance().removeAllWithStatus(Status.FAILED);
        updateUI(download);
        if (!downloadErrorShowing) {
            downloadErrorShowing = true;
            DialogUtils.showSingleButtonDialog("Download Error", DownloadConstants.handleFetchError(error, download), mContext, dialog -> downloadErrorShowing = false);
        }
    }

    @Override
    public void onDownloadBlockUpdated(@NotNull Download download, @NotNull DownloadBlock downloadBlock, int totalBlocks) {
        updateUI(download);
    }

    @Override
    public void onStarted(@NotNull Download download, @NotNull List<? extends DownloadBlock> list, int totalBlocks) {
        updateUI(download);
    }

    @Override
    public void onProgress(@NotNull Download download, long l, long l1) {
        updateUI(download);
    }

    @Override
    public void onPaused(@NotNull Download download) {
        updateUI(download);
    }

    @Override
    public void onResumed(@NotNull Download download) {
        updateUI(download);
    }

    @Override
    public void onCancelled(@NotNull Download download) {
        updateUI(download);
    }

    @Override
    public void onRemoved(@NotNull Download download) {
        updateUI(download);
    }

    @Override
    public void onDeleted(@NotNull Download download) {
        updateUI(download);
    }
}
