/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.auth.granter;

import org.springblade.core.oauth2.granter.TokenGranter;
import org.springblade.core.oauth2.granter.TokenGranterEnhancer;
import org.springblade.core.oauth2.granter.TokenGranterFactory;
import org.springblade.core.oauth2.props.OAuth2Properties;
import org.springblade.core.oauth2.provider.OAuth2Request;
import org.springblade.core.oauth2.provider.OAuth2Token;
import org.springblade.core.oauth2.service.OAuth2Client;
import org.springblade.core.oauth2.service.OAuth2User;

import java.util.List;

/**
 * IAM统一身份认证授权器工厂
 *
 * @author Chill
 */
public class IamAwareTokenGranterFactory extends TokenGranterFactory {

	private static final String AUTHORIZATION_CODE = "authorization_code";
	private static final String IAM_SSO = "iam_sso";

	private final IamSsoTokenGranter iamSsoTokenGranter;
	private final TokenGranter authorizationCodeGranter;
	private final List<TokenGranterEnhancer> tokenGranterEnhancers;

	public IamAwareTokenGranterFactory(List<TokenGranter> tokenGranters,
									   List<TokenGranterEnhancer> tokenGranterEnhancers,
									   OAuth2Properties properties) {
		super(tokenGranters, tokenGranterEnhancers, properties);
		this.iamSsoTokenGranter = tokenGranters.stream()
			.filter(IamSsoTokenGranter.class::isInstance)
			.map(IamSsoTokenGranter.class::cast)
			.findFirst()
			.orElse(null);
		this.authorizationCodeGranter = tokenGranters.stream()
			.filter(tokenGranter -> AUTHORIZATION_CODE.equals(tokenGranter.type()))
			.filter(tokenGranter -> !(tokenGranter instanceof IamSsoTokenGranter))
			.findFirst()
			.orElse(null);
		this.tokenGranterEnhancers = tokenGranterEnhancers;
	}

	@Override
	public TokenGranter create(String grantType) {
		if (IAM_SSO.equals(grantType) && iamSsoTokenGranter != null) {
			applyEnhancer(grantType, iamSsoTokenGranter);
			return iamSsoTokenGranter;
		}
		if (AUTHORIZATION_CODE.equals(grantType) && iamSsoTokenGranter != null && authorizationCodeGranter != null) {
			applyEnhancer(grantType, authorizationCodeGranter);
			applyEnhancer(IAM_SSO, iamSsoTokenGranter);
			return new IamAwareAuthorizationCodeGranter(iamSsoTokenGranter, authorizationCodeGranter);
		}
		return super.create(grantType);
	}

	private void applyEnhancer(String grantType, TokenGranter tokenGranter) {
		tokenGranterEnhancers.stream()
			.filter(enhancer -> grantType.equals(enhancer.type()))
			.findFirst()
			.ifPresent(tokenGranter::enhancer);
	}

	/**
	 * IAM授权码与本系统授权码分流
	 *
	 * @author Chill
	 */
	private static class IamAwareAuthorizationCodeGranter implements TokenGranter {

		private final IamSsoTokenGranter iamSsoTokenGranter;
		private final TokenGranter authorizationCodeGranter;
		private final ThreadLocal<TokenGranter> currentGranter = new ThreadLocal<>();

		private IamAwareAuthorizationCodeGranter(IamSsoTokenGranter iamSsoTokenGranter, TokenGranter authorizationCodeGranter) {
			this.iamSsoTokenGranter = iamSsoTokenGranter;
			this.authorizationCodeGranter = authorizationCodeGranter;
		}

		@Override
		public String type() {
			return AUTHORIZATION_CODE;
		}

		@Override
		public OAuth2Client client(OAuth2Request request) {
			return resolveGranter(request).client(request);
		}

		@Override
		public OAuth2User user(OAuth2Request request) {
			TokenGranter tokenGranter = resolveGranter(request);
			currentGranter.set(tokenGranter);
			return tokenGranter.user(request);
		}

		@Override
		public OAuth2Token token(OAuth2User user, OAuth2Request request) {
			try {
				return currentGranter.get().token(user, request);
			} finally {
				currentGranter.remove();
			}
		}

		@Override
		public void enhancer(TokenGranterEnhancer enhancer) {
			authorizationCodeGranter.enhancer(enhancer);
		}

		private TokenGranter resolveGranter(OAuth2Request request) {
			return iamSsoTokenGranter.supports(request) ? iamSsoTokenGranter : authorizationCodeGranter;
		}
	}

}
