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

import com.airlock.iam.base.misc.log.LogUtil;
import com.airlock.iam.plugin.api.annotation.property.RegexProperty;
import com.airlock.iam.plugin.api.annotation.property.RegexProperty.CaseSensitivitySelector;
import com.airlock.iam.plugin.api.util.PropertyDisplayNameReader;
import com.airlock.iam.plugin.configeditor.data.PropertyAdapter;
import com.airlock.iam.plugin.configeditor.field.MedusaRegexField;
import com.vaadin.v7.ui.Field;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

public class VaadinRegexPropertyRenderer extends VaadinPropertyRenderer<RegexProperty, String> {
   @SuppressFBWarnings("POTENTIAL_XML_INJECTION")
   @Override
   public Field<String> createField(PropertyAdapter<RegexProperty> propertyAdapter) {
      RegexProperty prop = (RegexProperty)propertyAdapter.getFieldAnnotation();
      MedusaRegexField field = new MedusaRegexField(propertyAdapter);
      String desc = renderDescription(
         propertyAdapter.getDisplayName(),
         prop.description() + getRegexpInfos(prop),
         prop.exampleValues(),
         prop.defaultValue(),
         propertyAdapter.getRequiredLicenseTags(),
         propertyAdapter.getPropertyName()
      );
      field.setInfo(desc);
      field.setRequired(!prop.optional());
      return field;
   }

   @SuppressFBWarnings("POTENTIAL_XML_INJECTION")
   public static String getRegexpInfos(RegexProperty prop) {
      StringBuilder desc = new StringBuilder(192);
      desc.append("<p><ul><li>Case sensitive: ");
      if (prop.caseSensitivity() == CaseSensitivitySelector.CASE_SENSITIVE) {
         desc.append("YES");
      } else if (prop.caseSensitivity() == CaseSensitivitySelector.CASE_INSENSITIVE) {
         desc.append("NO");
      } else if (prop.caseSensitivity() == CaseSensitivitySelector.CONFIGURED_BY_PROPERTY) {
         desc.append("defined by property ").append(LogUtil.quote(PropertyDisplayNameReader.propertyDisplayName(prop.caseSensitivityProperty())));
      }

      desc.append("</li><li>Multi-line matching: ").append(prop.isMultiLine() ? "YES" : "NO");
      desc.append("</li><li>Dot-all mode: ").append(prop.useDotAll() ? "YES" : "NO");
      desc.append("</li><li>Match against whole input: ").append(prop.matchAgainstWholeInput() ? "YES" : "NO").append("</li></ul></p>");
      return desc.toString();
   }
}
