package com.example.fuzzControll.service.impl;

import com.example.fuzzControll.conf.AflnetProperties;
import com.example.fuzzControll.constents.CmdConstent;
import com.example.fuzzControll.exception.testException.CmdException;
import com.example.fuzzControll.exception.fileExcption.FileException;
import com.example.fuzzControll.service.SeedFileService;
import com.example.fuzzControll.tools.test.TestCmdTools;
import com.example.fuzzControll.tools.file.FileTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@Service
public class SeedFileServiceImpl implements SeedFileService {
    TestCmdTools cmdTools = new TestCmdTools();
    FileTools fileTools = new FileTools();
    @Autowired
    AflnetProperties properties;

    @Override
    public List<String> getSeedFiles() throws CmdException {
        return cmdTools.runCmd(CmdConstent.GET_FILE_NAME + properties.getSeedPath(), "getSeedFiles");
    }

    //todo 同步修改可能会出现问题
    @Override
    public void delFile(String fileName) throws CmdException {
        int fileCountBefore = 0;
        int fileCountAfter = 0;
            fileCountBefore = getSeedFileCount("delFile before.");
            cmdTools.runCmd(CmdConstent.DELETE_FILE + properties.getSeedPath() + "/" + fileName, "delFile");
            fileCountAfter = getSeedFileCount("delFile after.");
        if (fileCountAfter == fileCountBefore) {
            throw new CmdException("Delete unsuccess ! The file has not changed .Attempt to change permissions or there is no filr to be deleted.");
        }
    }

    @Override
    public void upload(MultipartFile file) throws FileException, CmdException {

        int fileCountBefore = 0;
        int fileCountAfter = 0;
        fileCountBefore = getSeedFileCount("upload before.");
        fileTools.load(file);
        fileCountAfter = getSeedFileCount("upload after.");
        if (fileCountAfter == fileCountBefore) {
            throw new FileException("upload file error !The file failed to be submitted.Attempt to change permissions.Or thr file has been committed.");
        }
    }

    /**
     * 获取种子文件目录下文件数量
     */
    @Override
    public int getSeedFileCount(String msg) throws CmdException {
        int count = 0;
        try {
            List<String> files = cmdTools.runCmd(CmdConstent.GET_FILE_NAME + properties.getSeedPath(), "getSeedFileCount");
            count = files.size();
        } catch (CmdException e) {
            throw new CmdException(e.getMessage() + " when " + msg);
        }
        return count;
    }
}