/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.core.swagger;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

import org.springblade.core.secure.properties.JwtProperties;

import cn.hutool.extra.spring.SpringUtil;
import springfox.documentation.RequestHandler;
import springfox.documentation.service.ApiKey;

/**
 * Swagger工具类
 *
 * @author Chill
 */
public class SwaggerUtil {
	
	private static JwtProperties jwtProperties;

	/**
	 * 获取配置类
	 *
	 * @return jwtProperties
	 */
	private static JwtProperties getJwtProperties() {
		if (jwtProperties == null) {
			jwtProperties = SpringUtil.getBean(JwtProperties.class);
		}
		return jwtProperties;
	}

	public static Predicate<RequestHandler> basePackages(final String[] basePackages) {
		return input -> declaringClass(input).map(handlerPackage(basePackages)).orElse(true);
	}
	
	@SuppressWarnings("deprecation")
	private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
		return Optional.ofNullable(input.declaringClass());
	}

	private static Function<Class<?>, Boolean> handlerPackage(final String[] basePackages) {
		return input -> Stream.of(basePackages).anyMatch(f -> input.getPackage().getName().startsWith(f));
	}

	public static ApiKey bladeAuth() {
//		return new ApiKey(TokenConstant.HEADER, TokenConstant.HEADER, "header");
		String tokenHeader = getJwtProperties().getHeaderName();
		return new ApiKey(tokenHeader, tokenHeader, "header");
	}
}
