package com.yuchen.saas.park.service.pull.service;

import com.yuchen.saas.park.service.config.MinioParkConfig;
import com.yuchen.saas.park.service.pull.entity.FaceUploadResponse;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.nest.springwrap.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author 吕海泉
 * @create 2021/1/2 14:34
 */

@Component
public class FaceHandlerImpl implements FaceHandler {
    @Autowired
    private MinioParkConfig minioConfig;


    @Override
    public R<FaceUploadResponse> uploadFile(File file) throws InvalidPortException, InvalidEndpointException,
            IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException,
            InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException,
            XmlPullParserException, ErrorResponseException, XmlPullParserException, XmlPullParserException,
            XmlPullParserException, XmlPullParserException {
        if (file == null) {
            System.out.println("file----null");
        }

        String fileName = file.getName();
        // 文件类型
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        File tempFile = new File(String.valueOf(file));
        InputStream in = new FileInputStream(tempFile);
        // 生成新文件名，确保唯一性
        String picName = UUID.randomUUID().toString() + suffixName;

        MinioClient minioClient = new MinioClient(minioConfig.getEndpoint(),
                minioConfig.getApiKey(), minioConfig.getApiSecret());
//        minioClient.putObject("haiquan",objectName,new FileInputStream(tempFile),in.available(),fileType);
        minioClient.putObject(minioConfig.getFaceBucket(), picName, new FileInputStream(tempFile), in.available(),
                "image/jpg");
        return R.data(new FaceUploadResponse(picName,
                minioConfig.getFaceProxy() + "/" + picName
        ));
    }
}
