package co.pixelbeard.theanfieldwrap.audioPlayer;

import android.content.Context;
import android.util.Log;

import com.tonyodev.fetch2.Download;

import co.pixelbeard.theanfieldwrap.data.Podcast;
import co.pixelbeard.theanfieldwrap.data.RealmPodcast;
import co.pixelbeard.theanfieldwrap.data.responses.GenericResponse;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class AudioPlayerPresenter implements AudioPlayerContract.Presenter {

    private AudioPlayerContract.View mView;
    private DataRepository mRepo;

    public AudioPlayerPresenter(AudioPlayerContract.View view, DataRepository repo) {
        if (view != null && repo != null) {
            this.mView = view;
            this.mRepo = repo;

            mView.setPresenter(this);
        }
    }

    @Override
    public void downloadPodcast(Podcast podcast, Context context) {
        mRepo.downloadPodcast(podcast, context);
    }

    @Override
    public void savePodcast(Podcast podcast, Download download) {
        if (download.getUrl().equals(podcast.getPodcastFullUrl()) && download.getProgress() == 100) {
            mRepo.savePodcast(podcast, download.getFile());
        }
    }

    @Override
    public void recordAnalytic(String type, String variable, String secondVar) {
        mRepo.recordAnalytic(type, variable, secondVar).subscribe(new Observer<GenericResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(GenericResponse genericResponse) {
                if (genericResponse != null) {
                    Log.d("ANALYTIC: " + type, genericResponse.getMessage());
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public RealmPodcast getPodcastById(long id) {
        return mRepo.getPodcastByIdLocal(id);
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mRepo.onDestroyRepo();
    }

    @Override
    public void clearUserData(Context context) {
        //Not needed
    }
}
