package com.ycwl.basic.storage.adapters;

import com.ycwl.basic.storage.exceptions.UploadFileFailedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;

@Slf4j
public abstract class AStorageAdapter implements IStorageAdapter {

    @Override
    public String uploadFile(String contentType, File file, String ...path) {
        if (file == null) {
            return null;
        }
        try {
            InputStream inputStream = new FileInputStream(file);
            return uploadFile(contentType, inputStream, path);
        } catch (FileNotFoundException e) {
            throw new UploadFileFailedException("文件不存在");
        }
    }

    @Override
    public String uploadFile(MultipartFile file, String... path) {
        if (file == null) {
            return null;
        }
        try {
            InputStream inputStream = file.getInputStream();
            return uploadFile(file.getContentType(), inputStream, path);
        } catch (Exception e) {
            log.warn("文件上传失败", e);
            throw new UploadFileFailedException("文件上传失败");
        }
    }

    @Override
    public String getUrlForDownload(String... path) {
        return getUrlForDownload(new Date(System.currentTimeMillis() + 1000 * 60 * 60), path);
    }

    @Override
    public String getUrlForUpload(String... path) {
        return getUrlForUpload(new Date(System.currentTimeMillis() + 1000 * 60 * 60), "", path);
    }
}
