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

import gaf3.core.services.code.dao.GafCodeItemDAO
import gaf3.core.services.code.domain.CodeItem
import gaf3.core.services.code.service.CodeService
import gaf3.core.services.code.service.GafCodeStore
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

@Service("hybridCodeStore")
class HybridCodeStore(val itemDao: GafCodeItemDAO, val fileStore: FileCodeStore) : GafCodeStore {
    override fun load(type: String): List<CodeItem> {
        val item = itemDao.findOneByTypeAndAlias("group", type) ?: itemDao.findOneByTypeAndCode("group", type)
        return item?.let {
            val rs = itemDao.findAllByType(it.code ?: it.name ?: it.id!!, Sort.by(Sort.Direction.ASC, "code"))
            return rs.map { p ->
                CodeService.convertDomain(p)
            }
        } ?: fileStore.load(type)
    }
}