package com.ym.mec.thirdparty.storage.provider;

import java.io.File;
import java.io.IOException;

import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ksyun.ks3.dto.CannedAccessControlList;
import com.ksyun.ks3.dto.GetObjectResult;
import com.ksyun.ks3.dto.Ks3Object;
import com.ksyun.ks3.http.HttpClientConfig;
import com.ksyun.ks3.service.Ks3;
import com.ksyun.ks3.service.Ks3Client;
import com.ksyun.ks3.service.Ks3ClientConfig;
import com.ksyun.ks3.service.Ks3ClientConfig.PROTOCOL;
import com.ksyun.ks3.service.request.GetObjectRequest;
import com.ksyun.ks3.service.request.PutObjectRequest;
import com.ym.mec.thirdparty.exception.ThirdpartyException;
import com.ym.mec.thirdparty.storage.StoragePlugin;
import com.ym.mec.thirdparty.storage.StoragePluginContext;

@Component
public class KS3StoragePlugin implements StoragePlugin, InitializingBean, DisposableBean {

	public final static String PLUGIN_NAME = "Ksyun";

	@Value("${storage.oss.endpoint:ks3-cn-beijing.ksyun.com}")
	private String endpoint;

	@Value("${storage.oss.accessKeyId:AKLTtTeIbadpRG-pil4S0Q4m-Q}")
	private String accessKeyId;

	@Value("${storage.oss.accessKeySecret:OB1HmNOfDNW95wHoxMkP6IPFZXormk2ngA800TkvKAw7ozhiJGRqrMnnV8ZrAU3WRQ==}")
	private String accessKeySecret;

	@Value("${storage.oss.bucketName:daya}")
	private String bucketName;

	private Ks3 client;

	public String getName() {
		return PLUGIN_NAME;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Ks3ClientConfig config = new Ks3ClientConfig();
		config.setEndpoint(endpoint);// 如果使用自定义域名，设置endpoint为自定义域名，同时设置domainMode为true
		/**
		 * true：表示以自定义域名访问 
		 * false：表示以KS3的外网域名或内网域名访问
		 * 默认为false
		 */
		config.setDomainMode(false);
		config.setProtocol(PROTOCOL.http);

		/**
		 * true表示以   endpoint/{bucket}/{key}的方式访问
		 * false表示以  {bucket}.endpoint/{key}的方式访问
		 * 如果domainMode设置为true，pathStyleAccess可忽略设置
		 */
		config.setPathStyleAccess(false);
		HttpClientConfig hconfig = new HttpClientConfig();
		// 在HttpClientConfig中可以设置httpclient的相关属性，比如代理，超时，重试等。
		config.setHttpClientConfig(hconfig);
		client = new Ks3Client(accessKeyId, accessKeySecret, config);

		StoragePluginContext.addStoragePlugin(this);
	}

	@Override
	public String uploadFile(String folderName, File file) {
		if (!file.exists()) {
			throw new ThirdpartyException("需要上传的文件[{}]不存在", file.getAbsolutePath());
		}

		if (folderName.endsWith("/")) {
			folderName = folderName.substring(0, folderName.length() - 1);
		}

		PutObjectRequest request = new PutObjectRequest(bucketName, folderName + "/" + file.getName(), file);

		// 上传一个公开文件
		request.setCannedAcl(CannedAccessControlList.PublicRead);

		client.putObject(request);

		return "https://" + bucketName + "." + endpoint + "/" + folderName + "/" + file.getName();
	}

	@Override
	public byte[] getFile(String folderName, String fileName) throws IOException {
		GetObjectRequest request = new GetObjectRequest(bucketName, folderName + "/" + fileName);
		GetObjectResult result = client.getObject(request);

		Ks3Object object = result.getObject();
		try {
			return IOUtils.toByteArray(object.getObjectContent());
		} finally {
			if (object != null) {
				object.close();
			}
		}
	}

	@Override
	public void destroy() throws Exception {
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public static void main(String[] args) throws Exception {
		KS3StoragePlugin aliyunOssStorageService = new KS3StoragePlugin();
		aliyunOssStorageService.setAccessKeyId("LTAIwZW9XqrfsZ4r");
		aliyunOssStorageService.setAccessKeySecret("5uDsNZmHMxcnxav8w9byII4zcPpu5G");
		aliyunOssStorageService.setBucketName("yooma-test");
		aliyunOssStorageService.setEndpoint("oss-cn-beijing.aliyuncs.com");
		aliyunOssStorageService.afterPropertiesSet();

		File file = new File("e:/var/2.jpg");
		System.out.println(aliyunOssStorageService.uploadFile("aaa", file));

		System.err.println("***********" + aliyunOssStorageService.getFile("aaa", file.getName()).length);

		aliyunOssStorageService.destroy();
	}
}
