package com.qmth.boot.core.fss.service.impl;

import com.qmth.boot.core.constant.CoreConstant;
import com.qmth.boot.core.fss.config.FileStoreProperty;
import com.qmth.boot.core.fss.config.FssSecretProvider;
import com.qmth.boot.core.fss.service.FileStoreService;
import com.qmth.boot.core.fss.store.FileStore;
import com.qmth.boot.core.fss.utils.FileStoreBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PreDestroy;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

public class DefaultFileStoreService implements FileStoreService {

    private static final Logger log = LoggerFactory.getLogger(DefaultFileStoreService.class);

    private Map<String, FileStore> storeMap;

    public DefaultFileStoreService(Map<String, FileStoreProperty> map, @NotNull FssSecretProvider fssSecretProvider) {
        this.storeMap = new HashMap<>();
        if (map.isEmpty()) {
            log.warn("Property [" + CoreConstant.CONFIG_PREFIX + ".fss] is empty!");
            return;
        }
        for (Map.Entry<String, FileStoreProperty> entry : map.entrySet()) {
            storeMap.put(entry.getKey(),
                    FileStoreBuilder.buildFileStore(entry.getKey(), entry.getValue(), fssSecretProvider));
        }
    }

    public void close() {
        this.storeMap.clear();
    }

    @Override
    public FileStore getFileStore(String name) {
        return storeMap.get(name);
    }

    @PreDestroy
    public void shutdown() {
        for (FileStore store : storeMap.values()) {
            store.close();
        }
        storeMap.clear();
    }
}
