package com.qmth.boot.core.fss.config;

import com.qmth.boot.core.constant.CoreConstant;
import com.qmth.boot.core.fss.condition.FssCondition;
import com.qmth.boot.core.fss.service.FileService;
import com.qmth.boot.core.fss.service.impl.DefaultFileService;
import com.qmth.boot.core.fss.service.impl.SingletonFileService;
import com.qmth.boot.core.fss.store.FileStore;
import com.qmth.boot.core.fss.utils.FileStoreBuilder;
import com.qmth.boot.core.fss.utils.FssUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.validation.constraints.NotNull;

@Configuration
@ComponentScan("com.qmth.boot.core.fss")
public class FssAutoConfiguration {

    /**
     * 配置了多个FileStore的情况
     *
     * @return
     */
    @Bean
    @FssCondition(single = false)
    @ConfigurationProperties(prefix = CoreConstant.CONFIG_PREFIX)
    public FileStorePropertyMap fssMultiProperties() {
        return new FileStorePropertyMap();
    }

    @Bean(destroyMethod = "close")
    @FssCondition(single = false)
    public FileService fileService(FileStorePropertyMap fileStorePropertyMap, FssSecretProvider fssSecretProvider) {
        return new DefaultFileService(fileStorePropertyMap.getFss(), fssSecretProvider);
    }

    /**
     * 只配置了单个FileStore的情况
     *
     * @return
     */
    @Bean
    @FssCondition(single = true)
    @ConfigurationProperties(prefix = CoreConstant.CONFIG_PREFIX + ".fss")
    public FileStoreProperty fileStoreProperty() {
        return new FileStoreProperty();
    }

    @Bean(destroyMethod = "close")
    @FssCondition(single = true)
    public FileStore fileStore(FileStoreProperty fileStoreProperty, FssSecretProvider fssSecretProvider) {
        return FileStoreBuilder
                .buildFileStore(FssUtils.SINGLETON_FILE_STORE_NAME, fileStoreProperty, fssSecretProvider);
    }

    @Bean(destroyMethod = "close")
    @FssCondition(single = true)
    public FileService fileService(@NotNull FileStore fileStore) {
        return new SingletonFileService(fileStore);
    }
}
