/*
 * Copyright (c) 2017, 2018, Oracle America, Inc.
 *
 * The contents of this file are subject to the Apache License Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * If a copy of the Apache License Version 2.0 was not distributed with this file,
 * You can obtain one at https://www.apache.org/licenses/LICENSE-2.0.html
 */

package com.netflix.spinnaker.clouddriver.artifacts.oracle;

import com.netflix.spinnaker.credentials.CredentialsTypeProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty("artifacts.oracle.enabled")
@EnableConfigurationProperties(OracleArtifactProviderProperties.class)
@RequiredArgsConstructor
@Slf4j
class OracleArtifactConfiguration {
  private final OracleArtifactProviderProperties oracleArtifactProviderProperties;

  @Bean
  public CredentialsTypeProperties<OracleArtifactCredentials, OracleArtifactAccount>
      oracleCredentialsProperties(String clouddriverUserAgentApplicationName) {
    return CredentialsTypeProperties.<OracleArtifactCredentials, OracleArtifactAccount>builder()
        .type(OracleArtifactCredentials.CREDENTIALS_TYPE)
        .credentialsClass(OracleArtifactCredentials.class)
        .credentialsDefinitionClass(OracleArtifactAccount.class)
        .defaultCredentialsSource(oracleArtifactProviderProperties::getAccounts)
        .credentialsParser(
            a -> {
              try {
                return new OracleArtifactCredentials(clouddriverUserAgentApplicationName, a);
              } catch (Exception e) {
                log.warn("Failure instantiating oracle artifact account {}: ", a, e);
                return null;
              }
            })
        .build();
  }
}
