/*******************************************************************************
 * Copyright 2018 The MIT Internet Trust Consortium
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/

package cz.muni.ics.oauth2.model;

import com.nimbusds.jose.Algorithm;
import com.nimbusds.jose.Requirement;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

@Getter
@AllArgsConstructor
public enum PKCEAlgorithm {

	PLAIN(new Algorithm("plain", Requirement.REQUIRED)),
	S256(new Algorithm("S256", Requirement.OPTIONAL)),
	NONE(Algorithm.NONE);

	private final Algorithm algorithm;

	// map to aid reverse lookup
	private static final Map<String, PKCEAlgorithm> lookupByAlgName = new HashMap<>();
	private static final Map<Algorithm, PKCEAlgorithm> lookupByAlg = new HashMap<>();

	static {
		for (PKCEAlgorithm a : PKCEAlgorithm.values()) {
			lookupByAlg.put(a.algorithm, a);
			lookupByAlgName.put(a.algorithm.getName().toLowerCase(), a);
		}
	}

	public static PKCEAlgorithm getByAlgorithmName(String name) {
		if (!isSupported(name)) {
			throw new IllegalArgumentException("Unrecognized algorithm name: " + name);
		}
		name = name.toLowerCase();
		return lookupByAlgName.get(name);
	}

	public static boolean isSupported(String authMethod) {
		if (authMethod == null) {
			throw new IllegalArgumentException("authMethod must not be null");
		}
		authMethod = authMethod.toLowerCase();
		return lookupByAlgName.containsKey(authMethod);
	}

	public static PKCEAlgorithm getByAlgorithm(String name) {
		if (!isSupported(name)) {
			throw new IllegalArgumentException("Unrecognized value: " + name);
		}
		name = name.toLowerCase();
		return lookupByAlgName.get(name);
	}

	public static boolean isSupported(Algorithm alg) {
		if (alg == null) {
			throw new IllegalArgumentException("alg must not be null");
		}
		return lookupByAlg.containsKey(alg);
	}


}
