package br.com.trimsy.notify;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import org.json.JSONObject;

import java.util.Map;

public class TrimsyFcmService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String token) {
        if (token == null || token.length() == 0) return;
        getSharedPreferences(NotifyHub.PREFS, MODE_PRIVATE)
            .edit()
            .putString("fcm_token", token)
            .apply();
    }

    @Override
    public void onMessageReceived(RemoteMessage msg) {
        if (msg == null) return;
        String title = "Trimsy One";
        String body = "";
        if (msg.getNotification() != null) {
            if (msg.getNotification().getTitle() != null) title = msg.getNotification().getTitle();
            if (msg.getNotification().getBody() != null) body = msg.getNotification().getBody();
        }
        Map<String, String> data = msg.getData();
        if (data != null) {
            if (data.containsKey("title") && data.get("title") != null && data.get("title").length() > 0) {
                title = data.get("title");
            }
            if (data.containsKey("body") && data.get("body") != null && data.get("body").length() > 0) {
                body = data.get("body");
            }
        }
        String payload = "{}";
        try {
            JSONObject extra = new JSONObject();
            if (data != null) {
                for (String key : data.keySet()) extra.put(key, data.get(key));
            }
            payload = extra.toString();
        } catch (Exception ignored) {}
        int id = 1;
        try {
            if (data != null && data.containsKey("id")) {
                id = Integer.parseInt(String.valueOf(data.get("id")));
            } else {
                String raw = msg.getMessageId();
                if (raw == null || raw.length() == 0) raw = String.valueOf(System.currentTimeMillis());
                id = Math.abs(raw.hashCode());
            }
        } catch (Exception e) {
            id = Math.abs((int) System.currentTimeMillis());
        }
        if (id == 0) id = 1;
        NotifyHub.show(getApplicationContext(), id, title, body, payload);
    }
}
