package com.kickstarter.presenters;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.kickstarter.libs.Presenter;
import com.kickstarter.libs.RxUtils;
import com.kickstarter.models.Project;
import com.kickstarter.ui.activities.CheckoutActivity;
import com.kickstarter.ui.activities.ThanksActivity;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.subjects.PublishSubject;
import timber.log.Timber;

public class CheckoutPresenter extends Presenter<CheckoutActivity> {
  private final PublishSubject<Void> loginSuccess = PublishSubject.create();

  private Project project;

  @Override
  protected void onCreate(final Context context, final Bundle savedInstanceState) {
    super.onCreate(context, savedInstanceState);

    RxUtils.combineLatestPair(viewSubject, loginSuccess)
      .filter(pair -> pair.first != null)
      .take(1)
      .map(pair -> pair.first)
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(this::checkoutNext);
  }

  public void takeProject(final Project project) {
    this.project = project;
  }

  public void takeLoginSuccess() {
    loginSuccess.onNext(null);
  }

  public void takeCheckoutThanksUriRequest() {
    final Intent intent = new Intent(view(), ThanksActivity.class)
      .putExtra("project", project);
    view().startActivity(intent);
  }

  private void checkoutNext(final CheckoutActivity activity) {
    // In API < 19, can call loadUrl() with string "javascript:fn()"
    activity.webView.evaluateJavascript("root.checkout_next();", null);
  }
}

@@ -1450,56 +1450,21 @@
     
-// In API %3C 19, can call loadUrl() with s
+final S
 tring 
-%22
 java
@@ -1473,86 +1473,260 @@
 ript
-:fn()%22%0A    activity.webView.evaluateJavascript(%22root.checkout_next();%22, null);
+ = %22root.checkout_next();%22;%0A    if (android.os.Build.VERSION.SDK_INT %3E= android.os.Build.VERSION_CODES.KITKAT) %7B%0A      activity.webView.evaluateJavascript(javascript, null);%0A    %7D else %7B%0A      activity.webView.loadUrl(%22javascript:%22 + javascript);%0A    %7D
 %0A  %7D

Support API < 19 when evaluating javascript