package com.kickstarter.services.gcm;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.kickstarter.KSApplication;
import com.kickstarter.R;
import com.kickstarter.libs.CurrentUser;
import com.kickstarter.services.ApiClient;

import java.io.IOException;

import javax.inject.Inject;

import timber.log.Timber;

public class RegisterService extends IntentService {
  @Inject protected ApiClient apiClient;
  @Inject protected CurrentUser currentUser;

  public RegisterService() {
    super("RegisterService");
  }

  @Override
  public void onCreate() {
    super.onCreate();
    ((KSApplication) getApplicationContext()).component().inject(this);
  }

  @Override
  protected void onHandleIntent(@NonNull final Intent intent) {
    Timber.d("onHandleIntent");

    try {
      // This initially hits the network to retrieve the token, subsequent calls are local
      final InstanceID instanceID = InstanceID.getInstance(this);

      // R.string.gcm_defaultSenderId is derived from google-services.json
      final String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
      Timber.d("Token: " + token);

      sendTokenToApi(token);
      subscribeToGlobalTopic(token);
    } catch (final Exception e) {
      Timber.e("Failed to complete token refresh: " +  e.toString());
    }
  }

  /**
   * Persist token to app servers.
   *
   * @param token The new token.
   */
  private void sendTokenToApi(@NonNull final String token) {
    if (currentUser.observable().take(1).toBlocking().single() != null) {
      apiClient.registerPushToken(token).first().toBlocking().single();
    }
  }

  /**
   * Subscribe to generic global topic - not using more specific topics.
   *
   * @throws IOException if unable to reach the GCM PubSub service
   */
  private void subscribeToGlobalTopic(@NonNull final String token) throws IOException {
    GcmPubSub.getInstance(this).subscribe(token, "/topics/global", null);
  }
}


@@ -393,16 +393,99 @@
 ntUser;%0A
+import com.kickstarter.libs.utils.ObjectUtils;%0Aimport com.kickstarter.models.User;%0A
 import c
@@ -547,16 +547,39 @@
 ception;
+%0Aimport java.util.List;
 %0A%0Aimport
@@ -1836,12 +1836,8 @@
     
-if (
 curr
@@ -1860,16 +1860,23 @@
 le()
+%0A      
 .take(1)
 .toB
@@ -1875,42 +1875,92 @@
 e(1)
-.toBlocking().single() != null) %7B%0A
+%0A      .filter(ObjectUtils::isNotNull)%0A      .toBlocking()%0A      .subscribe(__ -%3E%0A  
     
@@ -2025,23 +2025,25 @@
 single()
-;
 %0A    
-%7D
+  );
 %0A  %7D%0A%0A  

Fix subscription