package eu.kanade.tachiyomi.ui.base.presenter;

import android.os.Bundle;
import android.support.annotation.Nullable;

import nucleus.factory.PresenterFactory;
import nucleus.presenter.Presenter;

public class NucleusConductorDelegate<P extends Presenter> {

    @Nullable private P presenter;
    @Nullable private Bundle bundle;
    private boolean presenterHasView = false;

    private PresenterFactory<P> factory;

    public NucleusConductorDelegate(PresenterFactory<P> creator) {
        this.factory = creator;
    }

    public P getPresenter() {
        if (presenter == null) {
            presenter = factory.createPresenter();
            presenter.create(bundle);
        }
        bundle = null;
        return presenter;
    }

    Bundle onSaveInstanceState() {
        Bundle bundle = new Bundle();
        getPresenter();
        if (presenter != null) {
            presenter.save(bundle);
        }
        return bundle;
    }

    void onRestoreInstanceState(Bundle presenterState) {
        if (presenter != null)
            throw new IllegalArgumentException("onRestoreInstanceState() should be called before onResume()");
        bundle = presenterState;
    }

    void onTakeView(Object view) {
        getPresenter();
        if (presenter != null && !presenterHasView) {
            //noinspection unchecked
            presenter.takeView(view);
            presenterHasView = true;
        }
    }

    void onDropView() {
        if (presenter != null && presenterHasView) {
            presenter.dropView();
            presenterHasView = false;
        }
    }

    void onDestroy() {
        if (presenter != null) {
            presenter.destroy();
        }
    }
}

@@ -339,55 +339,8 @@
 le;%0D
-%0A    private boolean presenterHasView = false;%0D
 %0A%0D%0A 
@@ -644,39 +644,32 @@
 e(bundle);%0D%0A    
-    %7D%0D%0A
         bundle =
@@ -676,16 +676,27 @@
  null;%0D%0A
+        %7D%0D%0A
         
@@ -1000,152 +1000,8 @@
  %7B%0D%0A
-        if (presenter != null)%0D%0A            throw new IllegalArgumentException(%22onRestoreInstanceState() should be called before onResume()%22);%0D%0A
     
@@ -1133,29 +1133,8 @@
 null
- && !presenterHasView
 ) %7B%0D
@@ -1215,46 +1215,8 @@
 );%0D%0A
-            presenterHasView = true;%0D%0A
     
@@ -1289,28 +1289,8 @@
 null
- && presenterHasView
 ) %7B%0D
@@ -1329,47 +1329,8 @@
 );%0D%0A
-            presenterHasView = false;%0D%0A
     

Simplify presenter delegate