package com.za.service.mqtt

import com.za.common.util.Tools.macSignature
import org.eclipse.paho.client.mqttv3.MqttConnectOptions

/**
 * A utility class that encapsulates the initialization parameters for the MQ4IOT client.
 */
class ConnectionOptionWrapper(
    instanceId: String,
    accessKey: String,
    clientId: String,
    secretKey: String? = null,
    tokenData: Map<String, String>? = null
) {
    /**
     * Internal connection parameters.
     */
    @JvmField
    val mqttConnectOptions: MqttConnectOptions = MqttConnectOptions().apply {
        isCleanSession = true
        keepAliveInterval = 90 // Keep alive interval in seconds
        isAutomaticReconnect = true
        mqttVersion = MqttConnectOptions.MQTT_VERSION_3_1_1
        connectionTimeout = 30 // Connection timeout in seconds
    }

    init {
        if (tokenData != null) {
            mqttConnectOptions.userName = "Token|$accessKey|$instanceId"
            mqttConnectOptions.password = buildTokenPassword(tokenData)
        } else if (secretKey != null) {
            mqttConnectOptions.userName = "Signature|$accessKey|$instanceId"
            mqttConnectOptions.password = macSignature(clientId, secretKey).toCharArray()
        }
    }

    /**
     * Builds the password for token authentication.
     */
    private fun buildTokenPassword(tokenData: Map<String, String>): CharArray {
        val builder = StringBuilder()
        for ((key, value) in tokenData) {
            builder.append(key).append("|").append(value).append("|")
        }
        if (builder.isNotEmpty()) {
            builder.setLength(builder.length - 1) // Remove the last '|'
        }
        return builder.toString().toCharArray()
    }
}
