package dp.kotul.solrapiapplication.repository

import dp.kotul.solrapiapplication.model.Language
import org.slf4j.Logger
import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.Cacheable
import org.springframework.jdbc.core.BeanPropertyRowMapper
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional

interface LanguageRepository {
    fun getLanguages(): List<Language>
}

const val CACHE_NAME_LANGUAGES = "LANGUAGES"

@Repository
@Transactional
class LanguageRepositoryImpl(val jdbcTemplate: NamedParameterJdbcTemplate, val log: Logger) : LanguageRepository {

    @Cacheable(cacheNames = [CACHE_NAME_LANGUAGES])
    override fun getLanguages(): List<Language> {
        return jdbcTemplate.query(
            "SELECT id, short_name FROM usr_language", BeanPropertyRowMapper(Language::class.java)
        )
    }

    @CacheEvict(allEntries = true, cacheNames = [CACHE_NAME_LANGUAGES])
    @Scheduled(fixedDelay = 3600000L)
    fun clearCollectionCache() {
        log.info("Clearing $CACHE_NAME_LANGUAGES repository cache")
    }
}
