package org.sky.resource.rule.oss;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.sky.core.literule.annotation.LiteRuleComponent;
import org.sky.core.literule.core.RuleComponent;
import org.sky.core.oss.OssTemplate;
import org.sky.core.oss.S3Template;
import org.sky.core.oss.props.OssProperties;
import org.sky.core.oss.rule.OssRule;
import org.sky.core.tool.utils.StringUtil;
import org.sky.resource.pojo.entity.Oss;
import org.sky.resource.rule.constant.OssRuleConstant;
import org.sky.resource.rule.context.OssContext;

/**
 * Amazon S3 云存储构建类
 *
 */
@LiteRuleComponent(id = OssRuleConstant.AMAZON_S3_RULE, name = "amazonS3OSS构建")
public class AmazonS3Rule extends RuleComponent {

	@Override
	public void process() {
		// 获取上下文
		OssContext contextBean = this.getContextBean(OssContext.class);
		Oss oss = contextBean.getOss();
		OssRule ossRule = contextBean.getOssRule();

		// 创建配置类
		OssProperties ossProperties = new OssProperties();
		ossProperties.setEndpoint(oss.getEndpoint());
		ossProperties.setTransformEndpoint(oss.getTransformEndpoint());
		ossProperties.setAccessKey(oss.getAccessKey());
		ossProperties.setSecretKey(oss.getSecretKey());
		ossProperties.setBucketName(oss.getBucketName());
		ossProperties.setRegion(oss.getRegion());
		// 创建客户端
		AWSCredentials credentials = new BasicAWSCredentials(ossProperties.getAccessKey(), ossProperties.getSecretKey());
		ClientConfiguration clientConfiguration = new ClientConfiguration();
		clientConfiguration.setSignerOverride("AWSS3V4SignerType");
		AmazonS3 amazonS3 = AmazonS3ClientBuilder
			.standard()
			.withEndpointConfiguration(new AwsClientBuilder.
				EndpointConfiguration(ossProperties.getEndpoint(),
				StringUtil.isBlank(ossProperties.getRegion()) ? Regions.DEFAULT_REGION.name() : Regions.fromName(ossProperties.getRegion()).getName()))
			.withPathStyleAccessEnabled(true)
			.withClientConfiguration(clientConfiguration)
			.withCredentials(new AWSStaticCredentialsProvider(credentials))
			.build();
		OssTemplate ossTemplate = new S3Template(amazonS3, ossRule, ossProperties);

		// 设置上下文
		contextBean.setOssTemplate(ossTemplate);

	}
}
