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

import cn.sagacloud.server.algorithm.models.config.MyProperties
import cn.sagacloud.server.algorithm.models.modelFile.ModelFile
import cn.sagacloud.server.algorithm.services.BaseDataService
import cn.sagacloud.server.algorithm.services.endpoint.ModelFileService
import com.sybotan.database.SFilter
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.time.Instant
import java.util.*
import kotlin.collections.ArrayList

@Component
class UploadState_0 : ModelState {

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

    val dataService = BaseDataService
    var modelList : ArrayList<ModelFile>? = null

    @Autowired
    lateinit var modelFileService: ModelFileService

    @Autowired
    lateinit var properties : MyProperties

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

    override fun handle() {
        try {
            if (modelList == null || modelList!!.isEmpty()) {
                return
            }
            modelList!!.forEach {
                if(it.createTime != null){
                    if(Instant.now().minusSeconds(60 * 60 * 24).compareTo(it.createTime!!.toInstant()) >= 0){
                        // 删除模型文件
                        modelFileService.removeFileFromFileServer(it)
                        // 删除记录并将楼层的模型文件退回上个版本
                        modelFileService.removeAndGoBack(it, properties, true, isMarkDelete = true)
                    }
                }
            }
        }catch (e : Exception){
            e.printStackTrace()
            logger.error(e.message)
        }
    }
}