package gaf3.core.services.code.service.impl

import com.alibaba.fastjson.JSON
import gaf3.core.exception.BusinessError
import gaf3.core.services.code.GafCodeConfigure
import gaf3.core.services.code.domain.CodeItem
import gaf3.core.services.code.service.GafCodeStore
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service

@Service("fileCodeStore")
// @ConditionalOnProperty(prefix = "gaf.code", name = ["store-type"], havingValue = "file", matchIfMissing = false)
class FileCodeStore(val config: GafCodeConfigure): GafCodeStore {
    override fun load(type: String): List<CodeItem> {
        val res = config.codePath.createRelative("${type}.json")
        if(!res.exists()) throw BusinessError(BusinessError.ERR_DATA_NOTEXIST, "字典数据文件不存")
        try {
            res.inputStream.bufferedReader().use {
                return JSON.parseArray(it.readText(), CodeItem::class.java).toList()
            }
        } catch (ex: Throwable) {
            log.debug("读取字典数据失败", ex)
            throw BusinessError(BusinessError.ERR_SERVICE_FAULT, "读取字典数据失败")
        }
    }
    companion object {
        val log: Logger = LoggerFactory.getLogger(FileCodeStore::class.java)
    }
}