package com.airlock.iam.plugin.configeditor.rendering;

import com.airlock.iam.plugin.api.annotation.property.PluginProperty;
import com.airlock.iam.plugin.api.exception.InitializeException;
import com.airlock.iam.plugin.api.valuereader.PluginPropertyValueReader;
import com.airlock.iam.plugin.configeditor.data.PropertyAdapter;
import com.airlock.iam.plugin.configeditor.field.MedusaPluginField;
import com.vaadin.v7.ui.Field;

public class VaadinPluginPropertyRenderer extends VaadinPropertyRenderer<PluginProperty, Object> {
   @Override
   public Field<Object> createField(PropertyAdapter<PluginProperty> propertyAdapter) {
      PluginProperty prop = (PluginProperty)propertyAdapter.getFieldAnnotation();
      MedusaPluginField mpf = new MedusaPluginField(propertyAdapter);
      mpf.setInfo(
         renderDescription(
            propertyAdapter.getDisplayName(),
            prop.description(),
            prop.defaultValue(),
            propertyAdapter.getRequiredLicenseTags(),
            propertyAdapter.getPropertyName()
         )
      );
      mpf.setRequired(!prop.optional());

      try {
         if (this.isGlobalReference(propertyAdapter)) {
            mpf.getInnerField()
               .initSelectablePluginsWithGlobalPluginReference(
                  propertyAdapter.getPluginConfiguration(), propertyAdapter.getConfigFieldType(), propertyAdapter.getConfigurationEnvironment()
               );
         } else if (prop.defaultValue() != Object.class) {
            mpf.getInnerField()
               .initSelectablePluginsWithDefaultPlugin(
                  propertyAdapter.getPluginConfiguration(),
                  propertyAdapter.getConfigFieldType(),
                  prop.defaultValue(),
                  propertyAdapter.getConfigurationEnvironment()
               );
         } else {
            mpf.getInnerField()
               .initSelectablePlugins(
                  propertyAdapter.getPluginConfiguration(), propertyAdapter.getConfigFieldType(), propertyAdapter.getConfigurationEnvironment()
               );
         }

         return mpf;
      } catch (InitializeException e) {
         throw new IllegalStateException(e);
      }
   }

   private boolean isGlobalReference(PropertyAdapter<PluginProperty> propertyAdapter) {
      return PluginPropertyValueReader.hasGlobalReference(propertyAdapter.getAnnotation(PluginProperty.class));
   }
}
