package com.rokid.renewcxrlsample.dataBean.selfView

/** Doc reference: chapter 08 custom page (openCustomView JSON: type, props, children). */
/**
 * Custom view tree node model.
 *
 * Describes full page by recursive `children` tree
 * and serializes to CXR custom-view protocol JSON.
 */
class SelfViewJson {
    // Node type, e.g. LinearLayout/TextView/ImageView.
    var type: String = ""
    // Node props as valid JSON string (generated by *Props.toJson()).
    var props: String = ""
    // Child node list that recursively builds the full view tree.
    var children: List<SelfViewJson>? = null

    /**
     * Serializes current node and its children.
     */
    fun toJson(): String {
        return if (type.isEmpty()){
            throw Exception("type is empty")
        }else{
            // Serialize to SDK structure: {"type":"...","props":{...},"children":[...]}
            val rb = StringBuilder("{").append("\"type\":\"$type\"")
                .append(",\"props\":$props")
            children?.let {
                rb.append(",\"children\":[")
                for (child in children!!){
                    rb.append(child.toJson())
                    rb.append(",")
                }
                rb.deleteCharAt(rb.length - 1)
                rb.append("]")
            }
            rb.append("}")
            rb.toString()
        }
    }
}