package com.kdanmobile.android.lib.material.tokens.category.spacing

import com.kdanmobile.android.lib.material.tokens.base.*
import com.kdanmobile.android.lib.material.tokens.category.IParseToken
import com.kdanmobile.android.lib.material.tokens.category.common.CommonXmlParserHandler
import org.json.JSONObject
import java.io.File

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2023/2/20
 * description: 解析alias-light.json 中Spacing 相关数据
 */
class AliasSpacingParse : IParseToken {
    var result = hashMapOf<String, String>()

    open var tag = "解析AliasSpacing"

    override fun parse(rootKey: String, jsonObject: JSONObject) {

        println("开始解析${rootKey}类型Tokens")
        for (itemKey in jsonObject.keys()) {
            val key = itemKey as String
            val value = jsonObject.get(key)
            val names = (value as JSONObject).names()
            if (names.length() == 2 && names.getString(0).equals("type") || names.getString(0).equals("value")) {
                val sizingValue = value.getString("value").replaceInvalidStr()
                result["${rootKey}_${key}"] = sizingValue
            } else {
                parse("${rootKey}_$key", value)
            }
        }
    }


    override fun generateTokenFile(destFilePath: String?) {
        if (destFilePath.isNullOrEmpty()) {
            logT(tag, "保存路径为空---return")
            return
        }
        logT(tag, "开始生成AliasSpacing Token文件")
        Log.t(tag, "token文件输出路径:${destFilePath}")

        val file = File(destFilePath)
        val resultData = FileUtil.parseAndMergeOldData(tag, file, CommonXmlParserHandler(XmlParserDataCategory.dimen), result)
            .sortedBy {
                it.first
            }
            .map {
                it.first to "@dimen/${it.second}"
            }
        FileUtil.writeTokens(file, XmlParserDataCategory.dimen, resultData)

        logT(tag, "解析生成文件完成-----")
    }


}