package com.sifang.modules.alioss;



import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.global.Global;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.sifang.modules.alioss.AliyunOSSClientUtil.getContentType;

public class S3ClientUtil {

    public static String uploadImage(byte[] b, String extName, String filename) {
        String dateFmt = new SimpleDateFormat("yyyyMMdd").format(new Date());

        if (extName != null && extName.startsWith(".")) {
            extName = extName.substring(1);
        }

        String fileName;
        if (StringUtil.isNotBlank(filename) && filename.startsWith(extName)) {
            fileName = filename;
        } else {
            fileName = IdGen.uuid() + "." + extName;
        }
        String filePath = OSSClientConstants.FOLDER + extName + "/" + dateFmt + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "/" + fileName;

        AmazonS3Client c = SpringUtils.getBean(AmazonS3Client.class);
        String name = Global.getConfig("s3.bucket");
        ObjectMetadata m = new ObjectMetadata();
        m.setContentLength(b.length);
        m.setContentType(getContentType("." + extName));
        String ctrl = Global.getConfig("s3.ctrl");
        if (StringUtils.isNotBlank(ctrl)) {
            m.setCacheControl(ctrl);
        }
        PutObjectRequest req = new PutObjectRequest(name, filePath, new ByteArrayInputStream(b), m);
        req.withCannedAcl(CannedAccessControlList.PublicRead);
        c.putObject(req);
        return filePath;
    }

}
