package net.northking.cctp.se.scheduler;

import lombok.extern.slf4j.Slf4j;
import net.northking.cctp.se.attach.AttachInfoUpload;
import net.northking.cctp.se.attach.AttachmentDB;
import net.northking.cctp.se.config.AtuServerConfig;
import net.northking.cctp.se.repository.AttachmentInfoRepository;
import net.northking.cctp.se.thread.AttachInfoExecutorPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>Title: AttachUploadScheduler</p>
 * <p>Description: 附件信息上传检查</p>
 *
 */
@Component
@Slf4j
public class AttachUploadScheduler {

    @Autowired
    private AtuServerConfig atuServerConfig;

    @Autowired
    private AttachmentInfoRepository repo;

    @Autowired
    private AttachInfoExecutorPool pool;

    /**
     * 附件信息检查
     * 初始延迟时间 20秒, 3秒检测一次
     */
    @Scheduled(initialDelay = 20 * 1000, fixedDelay = 3 * 1000)
    public void upload() {
        try {
            // 是否都空闲了
            if (!pool.isUploadAvailable()) {
                return;
            }
            // 查询前面20条数据
            Sort orderBy = Sort.by(Sort.Order.asc("failureTimes"), Sort.Order.asc("createdTime"));
            Pageable pageable = PageRequest.of(0, 10, orderBy);
            Page<AttachmentDB> resultPage = repo.findAll(pageable);
            List<AttachmentDB> content = resultPage.getContent();
            if (!content.isEmpty()) {
                for (AttachmentDB db : content) {
                    AttachInfoUpload uploadRunnable = new AttachInfoUpload(db);
                    pool.uploadTaskSubmit(uploadRunnable);
                }
            }
            // 便利
        }catch (Exception e){
            log.error("发送任务执行心跳异常", e);
        }
    }
}
