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

import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import com.airlock.iam.plugin.api.annotation.config.TestletInput;
import com.airlock.iam.plugin.api.config.LogTypes;
import com.airlock.iam.plugin.api.exception.PluginClassLoadingException;
import com.airlock.iam.plugin.api.testlet.Testlet;
import com.airlock.iam.plugin.impl.cache.PluginClassCache;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public final class TestletInputHelper {
   private static final ELogger LOG = ELoggerFactory.getLogger(TestletInputHelper.class);

   private TestletInputHelper() {
   }

   public static List<Field> findInputFields(Testlet testlet) throws IllegalArgumentException {
      List<Field> fields = new ArrayList<>();

      try {
         for (Field field : PluginClassCache.collectAllAnnotatedFields(testlet.getClass(), TestletInput.class)) {
            if (field.getAnnotation(TestletInput.class) != null) {
               if (!String.class.isAssignableFrom(field.getType())) {
                  throw new IllegalArgumentException("Fields in a testlet must be of type String. This is not the case with " + field.getName());
               }

               fields.add(field);
            }
         }

         return fields;
      } catch (PluginClassLoadingException e) {
         throw new IllegalStateException(e);
      }
   }

   public static void setInputValues(Testlet testlet, Map<Field, String> valueMap) {
      for (Entry<Field, String> entry : valueMap.entrySet()) {
         Field field = entry.getKey();

         try {
            field.setAccessible(true);
            field.set(testlet, entry.getValue());
         } catch (IllegalArgumentException | IllegalAccessException e) {
            LOG.error(LogTypes.CONFIGURATION_ERROR, e);
         }
      }
   }
}
