package co.pixelbeard.theanfieldwrap.downloads;

import android.content.Context;

import com.tonyodev.fetch2.Fetch;

import co.pixelbeard.theanfieldwrap.data.RealmPodcast;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.downloader.DownloadConstants;
import io.realm.Realm;

public class DownloadsPresenter implements DownloadsContract.Presenter {

    private DownloadsContract.View mView;
    private DataRepository mRepo;

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

            mView.setPresenter(this);
        } else {
            throw new RuntimeException();
        }
    }


    @Override
    public void getDownloadedPodcasts() {
        mRepo.getDownloadedPodcasts(podcasts -> {
            mView.setAdapter(podcasts);
        });
    }

    @Override
    public void deletePodcast(RealmPodcast podcast, int position) {


        Realm.getDefaultInstance().executeTransaction(realm -> {
            RealmPodcast realmPodcast = mRepo.getPodcastByIdLocal(podcast.getPostId());
            if (realmPodcast != null) {
                realmPodcast.deleteFromRealm();
            }
        });


        new Thread(() -> {
            String fileLocation = podcast.getFileLocation();

            DownloadConstants.deleteFileFromExternalStorage(fileLocation);


            Fetch.Impl.getDefaultInstance().getDownloads(result -> {
                for (int i = 0; i < result.size(); i++) {
                    if (result.get(i).getFile().equals(fileLocation)) {
                        Fetch.Impl.getDefaultInstance().remove(result.get(i).getId());
                        break;
                    }
                }
            });
        }).start();
    }

    @Override
    public void subscribe() {

    }

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

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