package com.voltek.producthuntclient.presenter;

import com.voltek.producthuntclient.model.entity.RealmPost;
import com.voltek.producthuntclient.presenter.contract.DetailsContract;
import com.voltek.producthuntclient.view.ui.MainActivity;
import com.voltek.producthuntclient.view.ui.WebFragment;

import io.reactivex.disposables.Disposable;
import timber.log.Timber;


public class DetailsPresenter extends DetailsContract.Presenter {

    private RealmPost mPost;

    public DetailsPresenter(DetailsContract.Navigator mNavigator, RealmPost post) {
        super(mNavigator);
        this.mPost = post;
    }

    @Override
    public void attach(DetailsContract.View view) {
        super.attach(view);

        Disposable getIt = mView.getIt()
                .subscribe(this::openWebsite, Timber::e);

        Disposable close = mView.close()
                .subscribe(this::closeDetails, Timber::e);

        mDisposable.addAll(getIt, close);

        mNavigator.changeTitle(mPost.getName());
        mView.showData(mPost);
    }

    private void openWebsite(Object o) {
        WebFragment webFragment = WebFragment.getInstance(mPost.getRedirectUrl());
        mNavigator.addFragment(webFragment, MainActivity.WEB_FRAGMENT_TAG);
    }

    private void closeDetails(Object o) {
        mNavigator.removeFragments();
    }
}
