package io.nexilis.service

import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import io.nexilis.service.core.Data
import io.nexilis.service.core.Incoming
import io.nexilis.service.core.Network
import io.nexilis.service.core.getSharedPreferences
import org.json.JSONObject

class FirebaseService : FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(tag, "onNewToken:$token")
        Api.sendToken(applicationContext, token)
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        Log.d(tag, "onMessageReceived:${message.data}")
        try {
            val json = JSONObject(message.data.toMap())
            json.optString("message_id").let { messageId ->
                applicationContext.getSharedPreferences().getString("pin", null)?.let { me ->
                    pullMessage(messageId, me)
                }
            }
        } catch (_: Exception) {

        }
    }

    private fun pullMessage(messageId: String, me: String) {
        Network().post(
            "https://digixplatform.com/pull_notification",
            "message_id=$messageId&pin=$me"
        ) { r, body ->
            if (r && !body.isNullOrEmpty()) {
                val data = JSONObject(body).optString("data")
                if (data.isNotEmpty()) {
                    val d = Data()
                    if (d.parse(data)) {
                        Incoming(applicationContext).process(d) {
                            if (it) {
                                Network().post(
                                    "https://digixplatform.com/ack_message",
                                    "message_id=$messageId&pin=$me"
                                ) { _, _ ->
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}