package com.p3.bewoplaner.data.firebase;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import com.p3.bewoplaner.BewoplanerApplication;
import com.p3.bewoplaner.data.api.responses.RegisterResponse;
import com.p3.bewoplaner.data.api.services.RegisterService;
import com.p3.bewoplaner.di.InjectionHelper;

import android.provider.Settings;
import android.util.Log;

import javax.inject.Inject;

import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by laszloffiferenc on 3/1/17.
 */
public class MessagingInstanceIdService extends FirebaseInstanceIdService {

    private static String TAG = "messaging";
    private static BewoplanerApplication sAndroidContext;

    @Inject
    RegisterService mRegisterService;

    public static void setApplicationContext(BewoplanerApplication androidContext) {
        sAndroidContext = androidContext;
    }

    @Override
    public void onTokenRefresh() {
        InjectionHelper.getMessagingComponent(sAndroidContext).inject(this);
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {
        mRegisterService.registerDevice(Settings.Secure.getString(sAndroidContext.getContentResolver(),
                Settings.Secure.ANDROID_ID), token)
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<RegisterResponse>() {
                    @Override
                    public void onCompleted() {
                        Log.d(TAG, "onCompleted: " + token);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError: ");
                    }

                    @Override
                    public void onNext(RegisterResponse registerResponse) {
                        Log.d(TAG, "onNext: ");
                    }
                });
    }
}