/*
 * Copyright (c) 2012-2018 Red Hat, Inc.
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.ide.oauth;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.eclipse.che.ide.api.oauth.OAuth2Authenticator;
import org.eclipse.che.ide.api.oauth.OAuth2AuthenticatorRegistry;
import org.eclipse.che.ide.util.loging.Log;

/**
 * Map based implementation of OAuth registry
 *
 * @author Vitalii Parfonov
 */
@Singleton
public class OAuth2AuthenticatorRegistryImpl implements OAuth2AuthenticatorRegistry {

  private final Map<String, OAuth2Authenticator> authenticators;

  @Inject
  public OAuth2AuthenticatorRegistryImpl(Set<OAuth2Authenticator> oAuth2Authenticators) {
    authenticators = new HashMap<>(oAuth2Authenticators.size());
    for (OAuth2Authenticator authenticator : oAuth2Authenticators) {
      final String providerName = authenticator.getProviderName();
      if (authenticators.get(providerName) != null) {
        Log.warn(
            OAuth2AuthenticatorRegistryImpl.class,
            "OAuth2Authenticator provider "
                + providerName
                + " already registered. But can be only one");
      } else {
        registerAuthenticator(providerName, authenticator);
      }
    }
  }

  @Override
  public void registerAuthenticator(String providerName, OAuth2Authenticator oAuth2Authenticator) {
    authenticators.put(providerName, oAuth2Authenticator);
  }

  @Override
  public OAuth2Authenticator getAuthenticator(String providerName) {
    return authenticators.get(providerName);
  }
}
