package com.jianshui.storage.factory;

import com.jianshui.common.exception.jianshui.JianshiSystemErrorException;
import com.jianshui.storage.service.IStorageService;
import com.jianshui.storage.service.StorageBaseAbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 存储工厂类
 * @Author 巩权林
 * @Date 2022-09-15 11:35
 **/
@Service
public class StorageFactory {

    @Autowired
    private final Map<String, StorageBaseAbstractService> storageFactory = new ConcurrentHashMap<>();

    /**
     * @param key
     * @return
     */
    public StorageBaseAbstractService getStorageInstance(String key) throws JianshiSystemErrorException {
        key = "storage_" + key;
        StorageBaseAbstractService factoryService = storageFactory.get(key);
        if (factoryService == null) {
            throw new JianshiSystemErrorException("当前存储服务不存在：" + key);
        }

        return factoryService;
    }


    /**
     * 初始化各存储实例
     */
    @PostConstruct
    public void initStorageInstance() {
        Iterator iterator = storageFactory.keySet().iterator();
        while (iterator.hasNext()) {
            StorageBaseAbstractService instance = storageFactory.get(iterator.next());
            instance.initInstance();
        }
    }
}
