package de.beyondsoft.ownchat.data.firebase;

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

import de.beyondsoft.ownchat.BewoplanerApplication;
import de.beyondsoft.ownchat.data.api.responses.RegisterResponse;
import de.beyondsoft.ownchat.data.api.services.RegisterService;
import de.beyondsoft.ownchat.di.InjectionHelper;

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

import javax.inject.Inject;

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

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: ");
                    }
                });
    }
}