/*
 * FcmRegistration
 *
 * (date unknown)
 *
 * Copyright (c) (year unknown) Steps Inc.  All rights reserved.
 */
package com.steps.tmuapp.lib;

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

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.messaging.FirebaseMessaging;
import com.steps.tmuapp.R;

import java.util.HashMap;
import java.util.Map;

import static com.steps.tmuapp.lib.PreferenceHelper.PREFERENCE_NOTIFICATION_TOKEN;
import static com.steps.tmuapp.lib.PreferenceHelper.PREFERENCE_USER_EMAIL;

import androidx.annotation.NonNull;

/**
 * A registrant to register the device ID to our message system for the
 * Google Firebase Cloud Messaging (FCM) service.
 *
 * @author (unknown), imacat
 */
public class FcmRegistration {

    /**
     * The tag for Log.d()
     */
    private static final String TAG = "=FcmRegistration=";

    /**
     * The activity to receive the message (the main activity is OK for this)
     */
    private final Context context;

    /**
     * The config helper
     */
    private final PreferenceHelper configHelper;

    /**
     * Constructs a new registrant the device ID to our message system.
     *
     * @param context The activity to receive the message (the main activity is OK for this)
     */
    public FcmRegistration(Context context) {
        this.context = context;
        // Manually initialize FirebaseApp
        if (FirebaseApp.getApps(this.context).isEmpty()) {
            FirebaseApp.initializeApp(this.context.getApplicationContext());
        }

        configHelper = new PreferenceHelper(this.context.getApplicationContext());
    }

    /**
     * Registers the device ID to our message system for the
     * Google Firebase Cloud Messaging (FCM) service.
     */
    public void registerPushServer() {
//        if (configHelper.getConfigString(PREFERENCE_Enable_Notification).equals("Y")) {
        FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
            @Override
            public void onComplete(@NonNull Task<String> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                    return;
                }

                // Get new FCM registration token
                String token = task.getResult();
                Log.d(TAG, "token => " + token);
                // Log and toast
                Log.d(TAG, "token => " + token);
                configHelper.setConfig(PREFERENCE_NOTIFICATION_TOKEN, token);
//                templateApp.setToken(token);
                String url = context.getString(R.string.push_server) + "/devices/AddDeviceWithDeviceID?";
                if (!configHelper.getConfigString(PREFERENCE_USER_EMAIL).isEmpty()) {
                    url += "user_uid=" + configHelper.getConfigString(PREFERENCE_USER_EMAIL) + "&";
                }
                url += "device_uuid=" + getDeviceID() + "&";
                url += "device_token=" + token + "&device_platform=android" + "&";
                url += "device_reception=1";
                Log.d(TAG, "registerServer: " + url);

                StringRequest registerToken = new StringRequest(Request.Method.GET, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                // Log.d("volley-get", response);
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "volley-get" + error.toString());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        return new HashMap<>();
                    }

                    @Override
                    public Map<String, String> getHeaders() {
                        return new HashMap<>();
                    }
                };
                Volley.newRequestQueue(context.getApplicationContext()).add(registerToken);
            }
        });
//        }
    }

    private String getDeviceID(){
        String android_id = Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID);
        Log.d(TAG, "android_id=" + android_id);
        return android_id;
    }
    /**
     * Obtains the boolean value from the resources.
     *
     * @param id Resource id for the boolean value
     * @return The boolean value
     */
    private Boolean getBoolean(int id) {
        return context.getResources().getBoolean(id);
    }
}
