package com.philisense.www.config;

import com.philisense.www.constant.Constants;
import com.philisense.www.enums.OssTypeEnum;
import com.philisense.www.utils.StringUtils;
import io.minio.MinioClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * 通用映射配置
 *
 */
@Configuration(value="uploadFileResourcesConfig")
public class FileResourcesConfig implements WebMvcConfigurer {

    @Resource
    private OssStorageProperties config;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 本地文件上传路径 */
        if(OssTypeEnum.LOCAL == config.getOssType()
                && StringUtils.isNotNull(config.getLocal())
                && StringUtils.isNotEmpty(config.getLocal().getPath())) {
            registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
                    .addResourceLocations("file:" + config.getLocal().getPath() + "/");
        }
    }

    /**
     * 开启跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路由
        registry.addMapping(Constants.RESOURCE_PREFIX  + "/**")
                // 设置允许跨域请求的域名
                .allowedOrigins("*")
                // 设置允许的方法
                .allowedMethods("GET");
    }

    /**
     * 注入minio 客户端
     * @return
     */
    @Bean("minioClient")
    public MinioClient minioClient(){
        if(OssTypeEnum.MINIO == config.getOssType()
                && StringUtils.isNotNull(config.getMinio())
                && StringUtils.isNotEmpty(config.getMinio().getAccessKey())
                && StringUtils.isNotEmpty(config.getMinio().getSecretKey())) {
            OssStorageProperties.MinioConfig minioConfig = config.getMinio();
            return MinioClient.builder()
                    .endpoint(minioConfig.getEndpoint())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
        }
        return null;
    }

}
