package com.ycwl.basic.storage;

import com.ycwl.basic.storage.adapters.AliOssAdapter;
import com.ycwl.basic.storage.adapters.AwsOssAdapter;
import com.ycwl.basic.storage.adapters.IStorageAdapter;
import com.ycwl.basic.storage.adapters.LocalStorageAdapter;
import com.ycwl.basic.storage.entity.StorageConfig;
import com.ycwl.basic.storage.enums.StorageType;
import com.ycwl.basic.storage.exceptions.StorageConfigException;
import com.ycwl.basic.storage.exceptions.StorageUndefinedException;
import com.ycwl.basic.storage.exceptions.StorageUnsupportedException;

import java.util.HashMap;
import java.util.Map;

public class StorageFactory {
    public static IStorageAdapter get(StorageType storageType, StorageConfig config) {
        IStorageAdapter adapter = get(storageType);
        adapter.setConfig(config);
        return adapter;
    }

    public static IStorageAdapter get(StorageType storageType) {
        return switch (storageType) {
            case LOCAL -> new LocalStorageAdapter();
            case AWS_OSS -> new AwsOssAdapter();
            case ALI_OSS -> new AliOssAdapter();
            default -> throw new StorageUnsupportedException(storageType.getType());
        };
    }

    public static IStorageAdapter get(String type) {
        StorageType storageType = StorageType.getStorageType(type);
        if (storageType == null) {
            throw new StorageUnsupportedException(type);
        }
        return get(storageType);
    }

    protected static Map<String, IStorageAdapter> namedStorage = new HashMap<>();
    protected static IStorageAdapter defaultStorage = null;

    public static void register(String name, IStorageAdapter adapter) {
        namedStorage.put(name, adapter);
    }

    public static IStorageAdapter use(String name) {
        IStorageAdapter adapter = namedStorage.get(name);
        if (adapter == null) {
            throw new StorageUndefinedException("未定义的存储方式："+name);
        }
        return adapter;
    }

    public static IStorageAdapter use() {
        if (defaultStorage == null) {
            throw new StorageConfigException("未定义默认存储方式");
        }
        return defaultStorage;
    }

    public static void setDefault(String defaultStorage) {
        StorageFactory.defaultStorage = use(defaultStorage);
    }
}
