package com.airlock.iam.plugin.framework.infrastructure.xstream;

import com.airlock.iam.plugin.framework.domain.model.property.SimpleProperty;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;

class SimplePropertyConverter extends AbstractPropertyConverter<SimpleProperty> {
   static final String TAG_PROPERTY_SIMPLE = "property";
   private static final String SECURE_EXTERNAL_STORAGE_ID_ATTR = "secureExternalStorageId";

   @Override
   protected Class<SimpleProperty> getPropertyClass() {
      return SimpleProperty.class;
   }

   protected SimpleProperty createNewProperty(String name, Optional<String> envid, Optional<String> context, Optional<String> variable) {
      return new SimpleProperty(name, envid, context, variable);
   }

   protected void unmarshalCustomAttributes(SimpleProperty property, HierarchicalStreamReader reader, UnmarshallingContext context) {
      property.setSecureExternalStorageId(StringUtils.trimToNull(reader.getAttribute("secureExternalStorageId")));
      property.setValue(StringUtils.trimToNull(reader.getValue()));
   }

   protected void marshalCustomAttributes(SimpleProperty property, HierarchicalStreamWriter writer, MarshallingContext context) {
      if (property.getValue().isPresent()) {
         writer.setValue(property.getValue().get());
      }

      XStreamHelper.writeAttributeIfValueIsPresent(writer, "secureExternalStorageId", property.getSecureExternalStorageId());
   }

   @Override
   protected String tagName() {
      return "property";
   }
}
