package com.atlassian.stash.internal.rest.content;

import com.atlassian.bitbucket.rest.util.StatefulJsonWriter;
import com.atlassian.bitbucket.content.AbstractContentTreeCallback;
import com.atlassian.bitbucket.content.ContentTreeContext;
import com.atlassian.bitbucket.content.ContentTreeNode;
import com.atlassian.bitbucket.content.ContentTreeSummary;
import com.atlassian.bitbucket.util.PageRequest;

import javax.annotation.Nonnull;
import java.io.IOException;

/**
 * @since 2.10
 */
public class JsonContentTreeCallback extends AbstractContentTreeCallback {

    private final StatefulJsonWriter writer;

    public JsonContentTreeCallback(StatefulJsonWriter writer) {
        this.writer = writer;
    }

    @Override
    public void onEnd(@Nonnull ContentTreeSummary summary) throws IOException {
        PageRequest current = summary.getPageRequest();
        PageRequest next = summary.getNextPageRequest();

        writer.endArray() //End values array
                .name("size").value(summary.getSize())
                .name("isLastPage").value(summary.isLastPage())
                .name("start").value(current.getStart())
                .name("limit").value(current.getLimit())
                .name("nextPageStart");
        if (next == null) {
            writer.nullValue();
        } else {
            writer.value(next.getStart());
        }
        writer.endObject();
    }

    @Override
    public void onStart(@Nonnull ContentTreeContext context) throws IOException {
        writer.beginObject()
                .name("values").beginArray();
    }

    @Override
    public boolean onTreeNode(@Nonnull ContentTreeNode node) throws IOException {
        if (node.getType() == ContentTreeNode.Type.FILE) {
            writer.value(node.getPath().toString());
        }

        return true;
    }
}
