package com.yonge.toolset.thirdparty.storage;

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

import com.ksyun.ks3.dto.PostObjectFormFields;
import com.yonge.toolset.thirdparty.entity.UploadSign;
import org.springframework.stereotype.Component;

import com.yonge.toolset.base.exception.ThirdpartyException;

@Component
public class StoragePluginContext {

    private static final Map<String, StoragePlugin> mapper = new HashMap<String, StoragePlugin>();

    public static void addStoragePlugin(StoragePlugin storagePlugin) {
        if (mapper.containsKey(storagePlugin.getName())) {
            throw new ThirdpartyException("存储插件:{}已存在", storagePlugin.getName());
        }
        mapper.put(storagePlugin.getName(), storagePlugin);
    }

    public String uploadFile(String storagePluginName, String folderName, File file) {
        StoragePlugin StoragePlugin = getStoragePlugin(storagePluginName);
        return StoragePlugin.uploadFile(folderName, file);
    }

    public String asyncUploadFile(String storagePluginName, String folderName, File file, boolean delLocalFile) {
        StoragePlugin StoragePlugin = getStoragePlugin(storagePluginName);
        return StoragePlugin.asyncUploadFile(folderName, file, delLocalFile);
    }

    public PostObjectFormFields getUploadSign(String storagePluginName, UploadSign uploadSign) {
        StoragePlugin StoragePlugin = getStoragePlugin(storagePluginName);
        return StoragePlugin.getUploadSign(uploadSign);
    }

    private StoragePlugin getStoragePlugin(String storagePluginName) {
        StoragePlugin storagePlugin = mapper.get(storagePluginName);

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

        return storagePlugin;
    }
}
