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 com.yonge.toolset.thirdparty.storage.provider.KS3StoragePlugin;
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);
    }

    public void setFileAcl(String storagePluginName,String fileName,Boolean isPublic,String bucketName){
        StoragePlugin storagePlugin = getStoragePlugin(storagePluginName);
        storagePlugin.setFileAcl(fileName,isPublic,bucketName);
    }

    public String getPublicUrl(String fileName,String bucketName){
        try {
            String substring = fileName.substring(0, fileName.lastIndexOf("?"));
            String substring1 = substring.substring(substring.lastIndexOf("/") + 1);
            this.setFileAcl(KS3StoragePlugin.PLUGIN_NAME,substring1,true,bucketName);
            return substring;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

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

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

        return storagePlugin;
    }
}
