package com.airlock.iam.security.certificate;

import com.google.common.base.Strings;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Objects;

public class PrivateKeyEntryBuilder implements KeyStoreEntryBuilder<PrivateKeyEntry> {
   public static final String DEFAULT_ENTRY_PASSWORD = "password";
   private String alias;
   private String password;
   private PrivateKey privateKey;
   private List<Certificate> chain = List.of();

   public PrivateKeyEntry build() {
      Objects.requireNonNull(this.alias);
      Objects.requireNonNull(this.password);
      Objects.requireNonNull(this.privateKey);
      Objects.requireNonNull(this.chain);
      Certificate[] certificates = this.chain.toArray(new Certificate[0]);
      return new PrivateKeyEntry(this.privateKey, certificates);
   }

   @Override
   public void addTo(KeyStore keyStore) throws KeyStoreException {
      String entryPassword = Strings.isNullOrEmpty(this.password) ? "password" : this.password;
      PrivateKeyEntry entry = this.build();
      keyStore.setEntry(this.alias, entry, new PasswordProtection(entryPassword.toCharArray()));
   }

   @SuppressFBWarnings(justification = "generated code")
   public String alias() {
      return this.alias;
   }

   @SuppressFBWarnings(justification = "generated code")
   public String password() {
      return this.password;
   }

   @SuppressFBWarnings(justification = "generated code")
   public PrivateKey privateKey() {
      return this.privateKey;
   }

   @SuppressFBWarnings(justification = "generated code")
   public List<Certificate> chain() {
      return this.chain;
   }

   @SuppressFBWarnings(justification = "generated code")
   public PrivateKeyEntryBuilder alias(String alias) {
      this.alias = alias;
      return this;
   }

   @SuppressFBWarnings(justification = "generated code")
   public PrivateKeyEntryBuilder password(String password) {
      this.password = password;
      return this;
   }

   @SuppressFBWarnings(justification = "generated code")
   public PrivateKeyEntryBuilder privateKey(PrivateKey privateKey) {
      this.privateKey = privateKey;
      return this;
   }

   @SuppressFBWarnings(justification = "generated code")
   public PrivateKeyEntryBuilder chain(List<Certificate> chain) {
      this.chain = chain;
      return this;
   }
}
