package com.cc.io

import org.dom4j.Attribute
import org.dom4j.Document
import org.dom4j.Element
import org.dom4j.io.SAXReader
import java.io.File

/**
 * 参考文章：http://blog.csdn.net/yyywyr/article/details/38359049
 */
class XmlManager {
    private val SPLIT_CHAR = "@"
    private val MODULE_NAME = "Module"
    private val TESTCASE_NAME = "TestCase"
    private val TEST_NAME = "Test"
    private val mConcernNodeNameList = mutableListOf(MODULE_NAME, TESTCASE_NAME, TEST_NAME)
    private val mConcernNodePropertyList = mutableListOf("name")

    private var mLastModuleName = ""
    private var mLastTestCaseName = ""
    private var mLastTestName = ""

    fun testCode() {
        // 1. 创建SAXReader对象
        val reader = SAXReader()
        // 2. 读取文件
        val file = File("D:\\Temp\\Cts_logs\\1.xml")
        // 3. 转换成Document
        val document : Document = reader.read(file)
        // 4. 获取根节点元素对象
        val root : Element = document.rootElement
        // 5. 遍历
        listNodes(root)
    }

    //遍历当前节点下的所有节点
    private fun listNodes(node: Element) {
        val isConcern = isConcernNode(node.name)
        log(isConcern, "当前节点的名称：" + node.name)
        // 5.1 首先获取当前节点的所有属性节点
        val list = node.attributes() as List<Attribute>
        // 5.2 遍历属性节点
        for (attribute in list) {
            val isConcernProperty = isConcernProperty(attribute.name)
            log(isConcernProperty, "属性" + attribute.name + ":" + attribute.value)
            if (isConcernProperty) {
                logMajorContent(node, attribute)
            }
        }
        // 5.3 如果当前节点内容不为空，则输出
        if (node.textTrim != "") {
            val isConcernProperty = isConcernProperty(node.name)
            log(isConcernProperty, node.name + "：" + node.text)
        }
        // 5.4 同时迭代当前节点下面的所有子节点
        // 5.5 使用递归
        val iterator = node.elementIterator()
        while (iterator.hasNext()) {
            val e = iterator.next() as Element
            listNodes(e)
        }
    }

    //只处理关心结点的信息
    private fun isConcernNode(nodeName: String) = nodeName in mConcernNodeNameList

    private fun isConcernProperty(propertyName : String) = propertyName in mConcernNodePropertyList

    private fun log(isConcern: Boolean, content: String) {
        // if (isConcern) println(content)
    }

    private fun logMajorContent(node:Element, attribute: Attribute) {
        when (node.name) {
            MODULE_NAME -> mLastModuleName = attribute.value
            TESTCASE_NAME -> mLastTestCaseName = attribute.value
            TEST_NAME -> {
                mLastTestName = attribute.value
                println(mLastModuleName + SPLIT_CHAR + mLastTestCaseName + SPLIT_CHAR + mLastTestName)
            }
        }
    }
}
