package ru.yandex.autodoc.common.out.json.builder;

import ru.yandex.autodoc.common.out.json.JsonObjectWriter;

/**
 * @author avhaliullin
 */
public class JsonNoTypePolymorphicBuilder<C extends ContainerBuilder> extends ContainerBuilder {
    private final JsonAppendable.NoTypePolymorphicHandler handler;
    private final C parent;

    public JsonNoTypePolymorphicBuilder(C parent, JsonAppendable appendable) {
        super(appendable);
        this.parent = parent;
        this.handler = appendable.polymorphic();
    }

    public JsonObjectBuilder<JsonNoTypePolymorphicBuilder<C>> withCase(String caseId) {
        assertState(State.READY);
        state = State.FOCUS_LOOSE;
        handler.withCase(caseId);
        return new JsonObjectBuilder<>(appendable, this, false, true);
    }

    public JsonNoTypePolymorphicBuilder<C> withCase(String caseId, JsonObjectWriter writer) {
        return writer.writeObject(withCase(caseId)).endObject();
    }

    @Override
    void focusReturn() {
        assertState(State.FOCUS_LOOSE);
        state = State.READY;
        handler.endCase();
    }

    public C endPolymorphic() {
        assertState(State.READY);
        state = State.CLOSED;
        return parent;
    }
}
