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

import com.airlock.iam.plugin.framework.domain.model.Plugin;
import com.airlock.iam.plugin.framework.domain.model.property.PluginProperty;
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;

class PluginPropertyConverter extends AbstractPropertyConverter<PluginProperty> {
   static final String TAG_PROPERTY_PLUGIN = "pluginProperty";

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

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

   protected void unmarshalCustomAttributes(PluginProperty property, HierarchicalStreamReader reader, UnmarshallingContext context) {
      if (reader.hasMoreChildren()) {
         reader.moveDown();
         property.setPlugin((Plugin)context.convertAnother(property, Plugin.class));
         reader.moveUp();
      }
   }

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

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