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

import ru.yandex.autodoc.common.out.json.JsonObjectWriter;
import ru.yandex.autodoc.common.util.enums.IEnumResolver;

import java.util.Collection;

/**
 * @author avhaliullin
 */
public class JsonPolymorphicBuilder<C extends ContainerBuilder, T> extends ContainerBuilder {
    private final JsonAppendable.PolymorphicHandler<T> handler;
    private final C parent;
    private final Collection<String> typeFieldComments;

    public JsonPolymorphicBuilder(C parent, JsonAppendable appendable, IEnumResolver<T> er, String typeFieldName, Collection<String> typeFieldComments) {
        super(appendable);
        this.parent = parent;
        this.handler = appendable.polymorphic(er, typeFieldName);
        this.typeFieldComments = typeFieldComments;
    }

    public JsonObjectBuilder<JsonPolymorphicBuilder<C, T>> withCase(T tpe) {
        assertState(State.READY);
        state = State.FOCUS_LOOSE;
        handler.withCase(tpe);
        for (String comment : typeFieldComments) {
            appendable.commentForLastKey(comment);
        }
        return new JsonObjectBuilder<>(appendable, this, false, false);
    }

    public JsonPolymorphicBuilder<C, T> withCase(T tpe, JsonObjectWriter writer) {
        return writer.writeObject(withCase(tpe)).endObject();
    }

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

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