package com.convenient.android.common.utils.dimens

import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.math.BigDecimal


/**
 * @classname：MakeUtils
 * @author：luozhipeng
 * @date：23/7/18 10:09
 * @description：
 */
object MakeUtils {

    private const val XML_HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
    private const val XML_RESOURCE_START = "<resources>\r\n"
    private const val XML_RESOURCE_END = "</resources>\r\n"
    private const val XML_DIMEN_TEMPLETE = "<dimen name=\"qb_%1\$spx_%2\$d\">%3$.2fdp</dimen>\r\n"
    private const val XML_BASE_DPI = "<dimen name=\"base_dpi\">%ddp</dimen>\r\n"
    private const val MAX_SIZE = 1600

    /**
     * 生成的文件名
     */
    private const val XML_NAME = "sw_dimens.xml"


    private fun px2dip(pxValue: Float, sw: Int, designWidth: Int): Float {
        val dpValue = pxValue / designWidth.toFloat() * sw
        val bigDecimal = BigDecimal.valueOf(dpValue.toDouble())
        return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toFloat()
    }

    /**
     * 生成所有的尺寸数据
     *
     * @param type
     * @return
     */
    private fun makeAllDimens(type: DimenTypes, designWidth: Int): String {
        return try {
            buildString {
                append(XML_HEADER)
                append(XML_RESOURCE_START)
                append(String.format(XML_BASE_DPI, type.swWidthDP))
                for (i in 0..MAX_SIZE){
                    val dpValue = px2dip(i.toFloat(), type.swWidthDP, designWidth)
                    append(String.format(XML_DIMEN_TEMPLETE, "", i, dpValue))
                }
                append(XML_RESOURCE_END)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    /**
     * 生成的目标文件夹
     * 只需传宽进来就行
     *
     * @param type     枚举类型
     * @param buildDir 生成的目标文件夹
     */
    fun makeAll(designWidth: Int, type: DimenTypes, buildDir: String) {
        var fos: FileOutputStream? = null
        try {
            //生成规则
            if (type.swWidthDP <=0) return
            val folderName = "values-sw" + java.lang.String.valueOf(type.swWidthDP) + "dp"

            //生成目标目录
            val file = File(buildDir + File.separator + folderName).apply {
                if (exists().not()){
                    mkdirs()
                }
            }

            //生成values文件
            fos = FileOutputStream(file.absolutePath + File.separator + XML_NAME)
            fos.write(makeAllDimens(type, designWidth).toByteArray())
            fos.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                fos?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}