package com.keao.edu.thirdparty.storage.provider;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
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.keao.edu.thirdparty.exception.ThirdpartyException;
import com.keao.edu.thirdparty.storage.StoragePlugin;
import com.keao.edu.thirdparty.storage.StoragePluginContext;
import com.qiniu.util.Auth;

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

	public final static String PLUGIN_NAME = "QiNiu";

	@Value("${storage.qiniu.kedo.accessKeyId:LTAI4Fdhxwfo7FsBDZKK8Wfv}")
	private String accessKeyId;

	@Value("${storage.qiniu.kedo.accessKeySecret:ERRma4P9VWbD98n93gspnZXmoq7rn5}")
	private String accessKeySecret;

	@Value("${storage.qiniu.kedo.bucketName:daya-online}")
	private String bucketName;

	private Auth auth;

	public String getName() {
		return PLUGIN_NAME;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		auth = Auth.create(accessKeyId, accessKeySecret);

		StoragePluginContext.addStoragePlugin(this);
	}

	@Override
	public String uploadFile(String folderName, File file) {
		String upToken = auth.uploadToken(bucketName, file.getName());
		if (StringUtils.isBlank(upToken)) {
			throw new ThirdpartyException("使用七牛-对象存储上传失败");
		}
		return String.format("%s/%s", bucketName, folderName + "/" + file.getName());
	}

	@Override
	public byte[] getFile(String folderName, String fileName) throws IOException {
		String encodedFileName = URLEncoder.encode(folderName + "/" + fileName, "utf-8").replace("+", "%20");
		String publicUrl = String.format("%s/%s", bucketName, encodedFileName);
		long expireInSeconds = 3600;// 1小时，可以自定义链接过期时间
		String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
		return FileUtils.readFileToByteArray(new File(finalUrl));
	}

	@Override
	public void destroy() throws Exception {

	}

	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 {

	}
}
