package com.airlock.iam.plugin.framework.misc.frompersistence;

import com.airlock.iam.plugin.api.exception.ConfigurationException;
import com.airlock.iam.plugin.framework.application.configuration.MutablePluginConfiguration;
import com.airlock.iam.plugin.framework.domain.model.Plugin;
import java.util.Optional;

class PluginTemplateResolver extends PluginRelationshipResolver {
   public PluginTemplateResolver(TranslationState translation) {
      super(translation);
   }

   @Override
   protected boolean duplicatesAllowed() {
      return true;
   }

   @Override
   protected boolean shouldOverwrite(String key, Plugin newValue, Plugin oldValue) {
      return false;
   }

   @Override
   protected Optional<String> determineIdentifier(Plugin plugin) {
      return plugin.getName();
   }

   protected PluginTemplateResolver.PluginNameIsNotUniqueException newIdentifierNotUniqueException(String id) {
      return new PluginTemplateResolver.PluginNameIsNotUniqueException(id);
   }

   @Override
   protected boolean needsToBeResolved(Plugin plugin) {
      return plugin.getTemplate().isPresent();
   }

   @Override
   protected void performAction(MutablePluginConfiguration referee, Plugin refereePlugin, MutablePluginConfiguration referenced) throws PersistenceModelToPCModelTranslation.PersistenceModelToPCModelTranslationException {
      this.setParentRelationship(referee, referenced);
   }

   private void setParentRelationship(MutablePluginConfiguration referee, MutablePluginConfiguration referenced) throws PersistenceModelToPCModelTranslation.CyclicTemplateRelationshipDetected {
      try {
         referee.setParentConfiguration(referenced);
      } catch (ConfigurationException e) {
         throw new PersistenceModelToPCModelTranslation.CyclicTemplateRelationshipDetected(referenced.getPluginDisplayName(), e);
      }
   }

   @Override
   protected String determineIDOfReferencedPlugin(Plugin plugin) {
      return plugin.getTemplate().get();
   }

   static class PluginNameIsNotUniqueException extends PersistenceModelToPCModelTranslation.PersistenceModelToPCModelTranslationException {
      PluginNameIsNotUniqueException(String notUniqueName) {
         super(String.format("The identifier %s is not unique. Have at least two plugins with this identifier.", notUniqueName));
      }
   }
}
