All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.vertx.codetrans.OptionsModel Maven / Gradle / Ivy

package io.vertx.codetrans;

import io.vertx.codegen.TypeInfo;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author Julien Viet
 */
public class OptionsModel extends ExpressionModel {

  public static ExpressionModel create(TypeInfo.Class type) {
    return forNew(args -> new OptionsModel(type));
  }

  private final TypeInfo.Class type;
  private final Map members;

  private OptionsModel(TypeInfo.Class type) {
    this(type, Collections.emptyMap());
  }

  private OptionsModel(TypeInfo.Class type, Map members) {
    this.type = type;
    this.members = members;
  }

  public TypeInfo.Class getType() {
    return type;
  }

  public Iterable getMembers() {
    return members.values();
  }

  @Override
  public ExpressionModel onMemberSelect(String identifier) {
    String name;
    Function memberFactory;
    if (identifier.length() > 3 && identifier.startsWith("set")) {
      name = Character.toLowerCase(identifier.charAt(3)) + identifier.substring(4);
      memberFactory = $ -> new Member.Single(render(name));
    } else if (identifier.length() > 3 && identifier.startsWith("add")) {
      name = Character.toLowerCase(identifier.charAt(3)) + identifier.substring(4) + "s"; // 's' for plural
      memberFactory = $ -> new Member.Array(render(name));
    } else {
      throw new UnsupportedOperationException("Not implemented");
    }
    return new ExpressionModel() {
      @Override
      public ExpressionModel onMethodInvocation(List arguments) {
        if (arguments.size() == 1) {
          Map copy = new LinkedHashMap<>(members);
          ExpressionModel value = arguments.get(0);
          Member member = copy.computeIfAbsent(name, memberFactory);
          member.append(value);
          copy.put(name, member);
          return new OptionsModel(type, copy);
        } else {
          throw new UnsupportedOperationException("not yet implemented");
        }
      }
    };
  }

  public void render(CodeWriter writer) {
    writer.getLang().renderOptions(this, writer);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy