package com.qmth.exam.reserve.service.impl;

import com.qmth.boot.core.fss.store.FileStore;
import com.qmth.boot.tools.models.ByteArray;
import com.qmth.exam.reserve.service.FileUploadService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private final static Logger log = LoggerFactory.getLogger(FileUploadServiceImpl.class);

    @Autowired
    private FileStore fileStore;

    @Override
    public void uploadFile(String dirName, File file) {
        try {
            fileStore.write(dirName, Files.newInputStream(file.toPath()), ByteArray.md5(file).toHexString());
        } catch (Exception e) {
            log.warn("文件上传出错", e);
        }
    }

    @Override
    public File downloadFile(String path, File localFile) {
        try {
            InputStream inputStream = fileStore.read(path);
            FileUtils.copyInputStreamToFile(inputStream, localFile);
        } catch (Exception e) {
            log.warn("下载文件出错", e);
        }
        return localFile;
    }

}
