package com.celements.structEditor.fields;

import static com.celements.structEditor.classes.OptionTagEditorClass.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.DocumentReference;

import com.celements.cells.attribute.AttributeBuilder;
import com.celements.model.access.exception.DocumentNotExistsException;
import com.google.common.base.Optional;

@Component(OptionTagPageType.PAGETYPE_NAME)
public class OptionTagPageType extends AbstractStructFieldPageType {

  private static Logger LOGGER = LoggerFactory.getLogger(OptionTagPageType.class);

  public static final String PAGETYPE_NAME = "OptionTag";

  static final String VIEW_TEMPLATE_NAME = "OptionTagView";

  @Override
  public String getName() {
    return PAGETYPE_NAME;
  }

  @Override
  protected String getViewTemplateName() {
    return VIEW_TEMPLATE_NAME;
  }

  @Override
  public Optional<String> defaultTagName() {
    return Optional.of("option");
  }

  @Override
  public void collectAttributes(AttributeBuilder attrBuilder, DocumentReference cellDocRef) {
    try {
      if (getFieldValue(cellDocRef, FIELD_SELECTED).or(false)) {
        attrBuilder.addEmptyAttribute("selected");
      }
      if (getFieldValue(cellDocRef, FIELD_DISABLED).or(false)) {
        attrBuilder.addEmptyAttribute("disabled");
      }
      attrBuilder.addNonEmptyAttribute("value", getNotEmptyString(cellDocRef, FIELD_VALUE).or(""));
      attrBuilder.addNonEmptyAttribute("label", getNotEmptyString(cellDocRef, FIELD_LABEL).or(""));
    } catch (DocumentNotExistsException exc) {
      LOGGER.error("cell doesn't exist '{}'", cellDocRef, exc);
    }
  }

}

@@ -436,16 +436,55 @@
 ptional;
+%0Aimport com.google.common.base.Strings;
 %0A%0A@Compo
@@ -1171,28 +1171,359 @@
 try %7B%0A      
-if (
+String cellValueStr = getStructDataEditorService().getCellValueAsString(cellDocRef).or(%22%22);%0A      if (!Strings.isNullOrEmpty(cellValueStr) && (cellValueStr.equals(getNotEmptyString(cellDocRef,%0A          FIELD_VALUE).or(%22%22)))) %7B%0A        attrBuilder.addEmptyAttribute(%22selected%22);%0A      %7D else if (Strings.isNullOrEmpty(cellValueStr) && 
 getFieldValu
@@ -1531,24 +1531,34 @@
 (cellDocRef,
+%0A         
  FIELD_SELEC

add selected when value is setted