package com.ycwl.basic.storage.starter;

import com.ycwl.basic.storage.StorageFactory;
import com.ycwl.basic.storage.adapters.IStorageAdapter;
import com.ycwl.basic.storage.starter.config.OverallStorageConfig;
import com.ycwl.basic.storage.starter.config.StorageConfigItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

@Configuration
public class StorageAutoConfiguration {
    private final OverallStorageConfig config;
    public StorageAutoConfiguration(OverallStorageConfig config) {
        this.config = config;
        if (config != null) {
            if (config.getConfigs() != null) {
                loadConfig();
            }
            if (StringUtils.isNotBlank(config.getDefaultUse())) {
                StorageFactory.setDefault(config.getDefaultUse());
            }
        }
    }

    private void loadConfig() {
        for (StorageConfigItem item : config.getConfigs()) {
            IStorageAdapter adapter = StorageFactory.get(item.getType());
            adapter.loadConfig(item.getConfig());
            StorageFactory.register(item.getName(), adapter);
        }
    }
}
