package cn.org.bjca.trust.push.message.msg

import cn.org.bjca.trust.push.enums.MsgType
import org.json.JSONException

abstract class Message {
    var messageId: String? = null
    var timestamp: Long = 0
    var fromClientId: String? = null
    var toClientId: String? = null
    var target: String? = null
    var msgType: MsgType = MsgType.UNKNOWN
    var message: String? = null
    var tenantNo: String? = null

    @Throws(JSONException::class)
    open fun parse(type: MsgType, sendMessage: SendMessage) {
        this.msgType = type
        this.messageId = sendMessage.messageId
        this.timestamp = sendMessage.timestamp
        this.fromClientId = sendMessage.fromClientId
        this.toClientId = sendMessage.toClientId
        this.target = sendMessage.target
        this.tenantNo = sendMessage.tenantNo
    }

    abstract fun createContentJsonStr(): String


    override fun toString(): String {
        val field = this.javaClass.declaredFields
        val sb = StringBuffer()
        sb.append("id: $messageId\n")
        sb.append("from: $fromClientId\n")
        sb.append("to: $toClientId\n")
        sb.append("type: $msgType\n")
        sb.append("timestamp: $timestamp\n")

        var i = 0
        while (i < field.size && field.isNotEmpty()) {
            field[i].isAccessible = true
            try {
                sb.append(
                    field[i].name + ": "
                            + (field[i][this]?.toString() ?: "--") + "\n"
                )
            } catch (e: IllegalArgumentException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            i++
        }
        return sb.toString()
    }
}