package cn.sagacloud.server.algorithm.backstage.state

import cn.sagacloud.server.algorithm.models.modelFile.ModelFile
import cn.sagacloud.server.algorithm.services.BaseDataService
import com.sybotan.database.SFilter
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.time.Instant
import java.util.*
import kotlin.collections.ArrayList

/**
 *
 *
 * @author jxing
 */
@Component
class SyncDataErrorState_31 : ModelState {

    companion object {
        // 日志
        private val logger = LoggerFactory.getLogger(UploadedState_1::class.java)
    } // Companion object

    val dataService = BaseDataService

    var modelList : ArrayList<ModelFile>? = null

    override fun prepareModel() {
        modelList = dataService.modelFileService.select(SFilter.eq("status", 31), SFilter.eq("removed", false)).exec()
    }

    /**
     * 将模型文件重试次数小于10次的模型文件放到
     */
    override fun handle() {
        try {
            if (modelList == null || modelList!!.isEmpty()) {
                return
            }
            modelList!!.forEach {
                if(it.syncRetryTimes != null){
                    // 重试次数小于100次, 且上次重试时间已经超过5分钟
                    if(it.syncRetryTimes!! < 100){
                        if(it.syncRetryDate != null) {
                            // 未超过5分钟
                            var times = 5
                            if(it.syncRetryTimes!! > 10){
                                times = it.syncRetryTimes!! + 20
                            }
                            if(Instant.now().minusSeconds((60 * times).toLong()).compareTo(it.syncRetryDate!!.toInstant()) < 0){
                                return@forEach
                            }
                        }
                        it.syncRetryDate = Date()
                        it.syncRetryTimes = it.syncRetryTimes!! + 1
                        it.status = 3
                        dataService.modelFileService.update(it, arrayListOf("status", "syncRetryTimes", "syncRetryDate"))
                    }
                }else{
                    it.syncRetryDate = Date()
                    it.syncRetryTimes = 1
                    it.status = 3
                    dataService.modelFileService.update(it, arrayListOf("status", "syncRetryTimes", "syncRetryDate"))
                }
            }
        }catch (e : Exception){
            e.printStackTrace()
            logger.error(e.message)
        }
    }
}