package com.ym.mec.thirdparty.storage;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.ym.mec.thirdparty.exception.ThirdpartyException;
import com.ym.mec.thirdparty.storage.vendors.AliyunOssStoragePlugin;

@Component
public class StoragePluginContext implements ApplicationContextAware, InitializingBean {

	@Value("${thirdparty.storagePluginName:aliyun}")
	private String storagePluginName;

	private ApplicationContext applicationContext;

	private final Map<String, String> mapper = new HashMap<String, String>() {
		/**
		 * 
		 */
		private static final long serialVersionUID = -9071481806931421021L;

		{
			put("aliyun", StringUtils.uncapitalize(AliyunOssStoragePlugin.class.getSimpleName()));
		}
	};

	private StoragePlugin storagePlugin;

	@Override
	public void afterPropertiesSet() throws Exception {
		if (StringUtils.isBlank(storagePluginName)) {
			throw new ThirdpartyException("存储插件变量thirdparty.storagePlugName不能为空");
		}

		storagePlugin = getStoragePlugin(storagePluginName);

		if (storagePlugin == null) {
			throw new ThirdpartyException("存储插件{}不存在", storagePluginName);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	/**
	 * 上传文件
	 * @param vendors 供应商
	 * @param folderName 文件夹
	 * @param file 需要上传的文件
	 * @return 返回文件路径
	 */
	public String uploadFile(String folderName, File file) {

		return storagePlugin.uploadFile(folderName, file);
	}

	/**
	 * 下载文件
	 * @param vendors 供应商
	 * @param folderName 文件夹
	 * @param fileName 文件名称
	 * @return 返回文件内容
	 * @throws IOException
	 */
	public byte[] getFile(String folderName, String fileName) throws IOException {

		return storagePlugin.getFile(folderName, fileName);
	}

	public void setStoragePluginName(String storagePluginName) {
		this.storagePluginName = storagePluginName;
	}

	private StoragePlugin getStoragePlugin(String vendors) {
		String beanId = mapper.get(vendors);

		if (StringUtils.isBlank(beanId)) {
			throw new ThirdpartyException("存储供应商不存在");
		}

		return applicationContext.getBean(beanId, StoragePlugin.class);
	}

}
