package com.mooctest.service;

import com.mooctest.dao.AggTaskStatusDao;
import com.mooctest.model.AggTaskStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Service
public class AggTaskStatusService {
    private static Logger logger = LoggerFactory.getLogger(AggTaskStatusService.class);
    @Autowired
    AggTaskStatusDao aggTaskStatusDao;

    public AggTaskStatus getByTaskId(long examId, long caseId) {
        String aggTaskId = genTaskId(examId, caseId);
        List<AggTaskStatus> aggTaskStatus = aggTaskStatusDao.findByTaskIdOrderByStartTimeDesc(aggTaskId);
        if (aggTaskStatus!= null && aggTaskStatus.size() > 0) {
            return aggTaskStatus.get(0);
        } else {
            return null;
        }

    }

    public AggTaskStatus create(long examId, long caseId) {
        String aggTaskId = genTaskId(examId, caseId);
        AggTaskStatus status = AggTaskStatus.builder()
                .taskId(aggTaskId)
                .status(0)
                .startTime(new Date())
                .build();
        return aggTaskStatusDao.save(status);

    }

    public AggTaskStatus updateStatus(String taskId, Date startTime) {
        AggTaskStatus aggTaskStatus = aggTaskStatusDao.findByTaskIdAndStartTime(taskId, startTime);
        if (aggTaskStatus != null) {
            aggTaskStatus.setStatus(1);
            aggTaskStatus.setEndTime(new Date());
            return aggTaskStatusDao.save(aggTaskStatus);
        } else {
            logger.error("AggTaskStatusService find null, taskId={}, startTime={}", taskId, startTime.getTime());
            return null;
        }
    }

    private String genTaskId(long examId, long caseId) {
        return examId + "-" + caseId;
    }
}
