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.FileStoreService;
import com.qmth.boot.core.fss.service.impl.DefaultFileStoreService;
import com.qmth.boot.core.fss.service.impl.SingletonFileStoreService;
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 org.springframework.lang.Nullable;

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();
    }

    /**
     * 只配置了单个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")
    public FileStoreService fileStoreService(@Nullable FileStore fileStore,
            @Nullable FileStorePropertyMap fileStorePropertyMap, @NotNull FssSecretProvider fssSecretProvider) {
        if (fileStore != null) {
            return new SingletonFileStoreService(fileStore);
        } else {
            return new DefaultFileStoreService(fileStorePropertyMap.getFss(), fssSecretProvider);
        }
    }
}
