package com.example.fuzzControll.service.impl;

import com.example.fuzzControll.conf.AflnetProperties;
import com.example.fuzzControll.constents.TableClassEnum;
import com.example.fuzzControll.exception.mysqlException.MysqlException;
import com.example.fuzzControll.mapper.AflnetMapper;
import com.example.fuzzControll.mapper.MissionInfoMapper;
import com.example.fuzzControll.domain.vo.AflnetResult;
import com.example.fuzzControll.domain.po.MissionInfo;
import com.example.fuzzControll.service.AflnetPersistenceService;
import com.example.fuzzControll.tools.file.FileTools;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service("AflnetPersistenceService")
public class AflnetPersistenceServiceImpl implements AflnetPersistenceService {
    @Autowired
    AflnetMapper aflnetMapper;
    @Autowired
    AflnetProperties aflnetProperties;
    @Autowired
    MissionInfoMapper missionInfoMapper;
    FileTools fileTools = new FileTools();

    @Override
    public int aflnetResultBackup(String filename,  int state, Long runTime) {
        return mysqlTransaction(filename, state, runTime);
    }

    @Override
    public void loadInFile(int missionId, String filePath) {
        AflnetResult aflnetResult = null;
        try {
            aflnetResult = aflnetMapper.selectResultById(missionId);
        } catch (MysqlException e) {
            e.printStackTrace();
            throw new MysqlException("AflnetMapper.selectResultById() Error!");
        }
        fileTools.loadFileInLocal(filePath, aflnetResult.getFileName(), aflnetResult.getFile());
    }

    @Transactional(rollbackFor = MysqlException.class)
    public int mysqlTransaction(String filename, int state, Long runTime) {
        int aflnetMissionId = SystemRunningParams.aflnetMissionId;//获取系统正在操作的aflnet的missionId
        AflnetResult result = new AflnetResult(aflnetMissionId, fileTools.fileReadAndTranstoBytes(aflnetProperties.getOutputPath(), filename), filename);
        aflnetMapper.aflnetOutputBackup(result);//存入日志文件
        missionInfoMapper.updateMission(state,runTime,aflnetMissionId);//更新该次任务的执行时间
        return 1;
    }
}