package gaf3.core.services.verify.service

import gaf3.core.cache.CacheService
import gaf3.core.services.verify.util.VerifyCodeHelper
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.util.Assert
import org.springframework.validation.annotation.Validated


@Service
@Validated
class VerifyCodeService (@Qualifier("gafVerifyCacheService") val cacheService : CacheService) {

    fun create(state: String): ByteArray {
        Assert.notNull(state, "必须提供状态码")
        var code = cacheService.getCache(state)
        if(code.isNullOrBlank()){
            code = VerifyCodeHelper.generateCode()
            cacheService.setCache(state, code)
        }
        return VerifyCodeHelper.generateImage(code)
    }

    fun verify(state: String, code: String): Boolean {
        val value: String? = cacheService.getCache(state)
        if(value == null) {
            log.debug("验证码[{}]不存在", state)
            return false
        }

        val res = code.compareTo(value, true) == 0
        if(res) {
            cacheService.delCache(state)
            log.debug("验证码[{}]比对成功, code:{}", state, code)
        } else {
            log.debug("验证码[{}]比对失败, code:{}, cache: {}", state, code, value)
        }
        return res
    }

    companion object {
        val log: Logger = LoggerFactory.getLogger(VerifyCodeService::class.java)
    }
}