package ru.forbion.f7cloud.core.push

import android.content.Intent
import android.os.Bundle

object F7PushIntentExtras {
    fun dataMap(extras: Bundle?): Map<String, String> {
        if (extras == null) return emptyMap()
        return buildMap {
            for (key in extras.keySet()) {
                if (key.startsWith("google.") || key == "from" || key == "collapse_key") continue
                extras.getString(key)?.takeIf { it.isNotBlank() }?.let { put(key, it) }
            }
        }
    }

    fun resolveOpenUrl(intent: Intent?): String? {
        if (intent == null) return null
        intent.getStringExtra(PushIntents.EXTRA_OPEN_URL)?.takeIf { it.isNotBlank() }?.let { return it }
        val data = dataMap(intent.extras)
        return data["acceptUrl"]
            ?: data["url"]
            ?: data["clickUrl"]
            ?: data["link"]
    }

    fun resolveRoomToken(intent: Intent?): String? {
        intent?.getStringExtra(PushIntents.EXTRA_ROOM_TOKEN)?.takeIf { it.isNotBlank() }?.let { return it }
        return dataMap(intent?.extras)["roomToken"]
    }

    fun resolveMessageId(intent: Intent?): String? {
        intent?.getStringExtra(PushIntents.EXTRA_MESSAGE_ID)?.takeIf { it.isNotBlank() }?.let { return it }
        return dataMap(intent?.extras)["messageId"]
    }

    fun publishEventFromIntent(intent: Intent?) {
        val data = dataMap(intent?.extras)
        if (data.isEmpty()) return
        val title = data["title"] ?: "F7cloud"
        val body = data["body"] ?: ""
        F7PushEventHub.publish(F7PushEventParser.parse(data, title, body))
    }

    fun isFcmLaunch(intent: Intent?): Boolean {
        val extras = intent?.extras ?: return false
        return extras.containsKey("google.message_id") || dataMap(extras).isNotEmpty()
    }
}
