package com.dji.sample.component.oss.service.impl;

import com.dji.sample.component.oss.model.OssConfiguration;
import com.dji.sample.component.oss.service.IOssService;
import com.dji.sdk.cloudapi.storage.CredentialsToken;
import com.dji.sdk.cloudapi.storage.OssTypeEnum;
import io.minio.*;
import io.minio.credentials.AssumeRoleProvider;
import io.minio.credentials.Credentials;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

import static com.dji.sample.common.util.IPUtils.isLanIp;

/**
 * @author sean
 * @version 0.3
 * @date 2021/12/23
 */
@Service
@Slf4j
public class MinIOServiceImpl implements IOssService {

    private MinioClient client;

    private MinioClient localClient;

    @Override
    public OssTypeEnum getOssType() {
        return OssTypeEnum.MINIO;
    }

    @Override
    public CredentialsToken getCredentials() {
        // 根据ip 是否局域网
        boolean isLanIp = isLanIp();
        String endpoint;
        if (isLanIp) {
            endpoint = OssConfiguration.endpoint;
        } else {
            endpoint = OssConfiguration.localEndpoint;
        }
        try {
            AssumeRoleProvider provider = new AssumeRoleProvider(endpoint, OssConfiguration.accessKey,
                    OssConfiguration.secretKey, Math.toIntExact(OssConfiguration.expire),
                    null, OssConfiguration.region, null, null, null, null);
            Credentials credential = provider.fetch();
            return new CredentialsToken(credential.accessKey(), credential.secretKey(), credential.sessionToken(), OssConfiguration.expire);
        } catch (NoSuchAlgorithmException e) {
            log.debug("Failed to obtain sts.");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public URL getObjectUrl(String bucket, String objectKey) {
        // 根据ip 是否局域网
        boolean isLanIp = isLanIp();
        MinioClient client;
        if (isLanIp) {
            client = this.localClient;
        } else {
            client = this.client;
        }
        return getObjectUrl(client, bucket, objectKey);
    }

    @Override
    public URL getObjectLocalUrl(String bucket, String objectKey) {

        return getObjectUrl(this.localClient, bucket, objectKey);
    }
    @Override
    public URL getObjectNetUrl(String bucket, String objectKey) {

        return getObjectUrl(this.client, bucket, objectKey);
    }
    public URL getObjectUrl(MinioClient client, String bucket, String objectKey) {
        try {
            return new URL(
                    client.getPresignedObjectUrl(
                            GetPresignedObjectUrlArgs.builder()
                                    .method(Method.GET)
                                    .bucket(bucket)
                                    .object(objectKey)
                                    .expiry(Math.toIntExact(OssConfiguration.expire))
                                    .build()));
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidKeyException | InvalidResponseException | IOException |
                NoSuchAlgorithmException | XmlParserException | ServerException e) {
            throw new RuntimeException("The file does not exist on the OssConfiguration.");
        }
    }

    @Override
    public Boolean deleteObject(String bucket, String objectKey) {
        // 根据ip 是否局域网
        boolean isLanIp = isLanIp();
        MinioClient client;
        if (isLanIp) {
            client = this.localClient;
        } else {
            client = this.client;
        }
        try {
            client.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectKey).build());
        } catch (MinioException | NoSuchAlgorithmException | IOException | InvalidKeyException e) {
            log.error("Failed to delete file.");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public InputStream getObject(String bucket, String objectKey) {
        // 根据ip 是否局域网
        boolean isLanIp = isLanIp();
        MinioClient client;
        if (isLanIp) {
            client = this.localClient;
        } else {
            client = this.client;
        }
        try {
            GetObjectResponse object = client.getObject(GetObjectArgs.builder().bucket(bucket).object(objectKey).build());
            return new ByteArrayInputStream(object.readAllBytes());
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
            e.printStackTrace();
        }
        return InputStream.nullInputStream();
    }

    @Override
    public void putObject(String bucket, String objectKey, InputStream input) {
        // 根据ip 是否局域网
        boolean isLanIp = isLanIp();
        MinioClient client;
        if (isLanIp) {
            client = this.localClient;
        } else {
            client = this.client;
        }
        try {
            client.statObject(StatObjectArgs.builder().bucket(bucket).object(objectKey).build());
            throw new RuntimeException("The filename already exists.");
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.info("The file does not exist, start uploading.");
            try {
                ObjectWriteResponse response = client.putObject(
                        PutObjectArgs.builder().bucket(bucket).object(objectKey).stream(input, input.available(), 0).build());
                log.info("Upload FlighttaskCreateFile: {}", response.etag());
            } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException ex) {
                log.error("Failed to upload FlighttaskCreateFile {}.", objectKey);
                ex.printStackTrace();
            }
        }
    }

    public void createClient() {
        if (Objects.nonNull(this.client)) {
        } else {
            this.client = MinioClient.builder()
                    .endpoint(OssConfiguration.endpoint)
                    .credentials(OssConfiguration.accessKey, OssConfiguration.secretKey)
                    .region(OssConfiguration.region)
                    .build();
        }
        // 增加 本地连接
        try {
            if (Objects.nonNull(this.localClient)) {
            } else {
                this.localClient = MinioClient.builder()
                        .endpoint(OssConfiguration.localEndpoint)
                        .credentials(OssConfiguration.accessKey, OssConfiguration.secretKey)
                        .region(OssConfiguration.region)
                        .build();
            }
        } catch (Exception e) {
            log.error("createClient Exception: ", e);
        }

    }
}
