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

import com.airlock.iam.plugin.api.annotation.property.StringProperty;
import com.airlock.iam.plugin.configeditor.data.PropertyAdapter;
import com.airlock.iam.plugin.configeditor.field.MedusaEnumField;
import com.airlock.iam.plugin.configeditor.field.MedusaField;
import com.airlock.iam.plugin.configeditor.field.MedusaPasswordField;
import com.airlock.iam.plugin.configeditor.field.MedusaTextAreaField;
import com.airlock.iam.plugin.configeditor.field.MedusaTextField;
import com.vaadin.v7.ui.Field;
import java.lang.annotation.Annotation;

public class VaadinStringPropertyRenderer extends VaadinPropertyRenderer<StringProperty, Object> {
   @Override
   public Field<Object> createField(PropertyAdapter<StringProperty> propertyAdapter) {
      StringProperty prop = (StringProperty)propertyAdapter.getFieldAnnotation();
      MedusaField<? extends Annotation, ?> field;
      if (prop.isMultiLineText()) {
         field = new MedusaTextAreaField(propertyAdapter);
      } else if (prop.isSensitive()) {
         field = new MedusaPasswordField(propertyAdapter);
      } else {
         String[] allowedValues = prop.allowedValues();
         String[] suggestedValues = prop.suggestedValues();
         if (allowedValues.length > 0) {
            MedusaEnumField enumField = new MedusaEnumField(propertyAdapter, false);
            enumField.fillStrings(allowedValues);
            field = enumField;
         } else if (suggestedValues.length > 0) {
            MedusaEnumField enumField = new MedusaEnumField(propertyAdapter, true);
            enumField.fillStrings(suggestedValues);
            field = enumField;
         } else {
            field = new MedusaTextField(propertyAdapter);
         }
      }

      field.setInfo(
         renderDescription(
            propertyAdapter.getDisplayName(),
            prop.description(),
            prop.exampleValues(),
            prop.defaultValue(),
            propertyAdapter.getRequiredLicenseTags(),
            propertyAdapter.getPropertyName()
         )
      );
      field.setRequired(!prop.optional());
      return field;
   }
}
