package ru.yandex.autotests.direct.utils.clients.s3;

import java.io.File;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.model.PutObjectResult;

import ru.yandex.autotests.direct.utils.config.DirectTestTvmSecret;

public class S3Helper {
    static final long S3_TVM_ID_PROD = 2017579;
    private static final ClientConfiguration CLIENT_CONF = new ClientConfiguration()
            .withConnectionTimeout(5_000)
            .withRequestTimeout(60_000)
            .withMaxErrorRetry(3)
            .withMaxConnections(5);
    public static String PUBLIC_BUCKET = "direct-qa-pub";
    public static String TTL_PREFIX = "03c305791e/";
    private static S3Helper instance;
    private final AmazonS3 client;


    private S3Helper(AmazonS3 client) {
        this.client = client;
    }

    public static S3Helper getInstance() {
        if (instance == null) {
            instance = new S3Helper(createClient());
        }
        return instance;
    }

    private static AmazonS3 createClient() {
        AWSCredentialsProvider s3TvmCredentials = new TvmCredentialsProvider(DirectTestTvmSecret.getInstance());
        AmazonS3Client amazonS3Client = new AmazonS3Client(s3TvmCredentials, CLIENT_CONF);
        amazonS3Client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).disableChunkedEncoding().build());
        amazonS3Client.setRegion(Region.getRegion(Regions.US_EAST_1));
        amazonS3Client.setEndpoint("s3.mds.yandex.net");
        return amazonS3Client;
    }

    public String getTemporaryUrl(String key) {
        return "https://" + PUBLIC_BUCKET + ".s3.yandex.net/" + TTL_PREFIX + key;
    }

    public String putTemporaryObject(String key, File file) {
        client.putObject(PUBLIC_BUCKET, TTL_PREFIX + key, file);
        return getTemporaryUrl(key);
    }

    public void deleteTemporaryObject(String key) {
        client.deleteObject(PUBLIC_BUCKET, TTL_PREFIX + key);
    }

    public AmazonS3 getClient() {
        return client;
    }
}
