package cn.sagacloud.server.algorithm.services.json

import cn.sagacloud.server.algorithm.models.entities.Unit
import cn.sagacloud.server.algorithm.models.jsonAnalyzer.AllComponents
import cn.sagacloud.server.algorithm.models.jsonAnalyzer.BaseObj
import cn.sagacloud.server.algorithm.models.modelFile.ModelFile
import com.sybotan.service.SObjectService

/**
 *
 *
 * @author jxing
 */
object ModelAnalyzer {

    fun analyze(modelService: SObjectService<ModelFile>, modelFile: ModelFile, baseObj: BaseObj<AllComponents>?) : Boolean {
        modelFile.planName = baseObj!!.planName
        if(baseObj.mbiName != null && baseObj.mbiName!!.startsWith("Pj") && baseObj.mbiName!!.length > 11){
            modelFile.mbiName = baseObj.mbiName
            modelFile.projectId = baseObj.mbiName!!.substring(0, 12)
        }
        val unit = findLengthUnit(baseObj)
        if(unit != null){
            modelFile.units = unit
        }
        modelFile.baseLevel = baseObj.baseLevel
        return modelService.update(modelFile)
    }

    private fun findLengthUnit(baseObj: BaseObj<AllComponents>) : Unit? {
        val units = baseObj.elements!!.units ?: return null
        for(item in units){
            if(item.name == null)
                continue
            if(item.name.toLowerCase() == "length"){
                return item
            }
        }
        return null
    }
}