package com.atlassian.bitbucket.content;

import com.atlassian.bitbucket.util.PageUtils;
import com.google.common.collect.Lists;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.List;

import static java.util.Objects.requireNonNull;

public class DirectoryRevisionContentTreeCallback extends AbstractContentTreeCallback {

    private final String path;
    private final String commitId;
    private final List<ContentTreeNode> nodes;

    private DirectoryRevision revision;

    public DirectoryRevisionContentTreeCallback(@Nullable String path, @Nonnull String commitId) {
        this.path = path;
        this.commitId = requireNonNull(commitId, "commitId");

        nodes = Lists.newArrayList();
    }

    @Override
    public void onEnd(@Nonnull ContentTreeSummary summary) throws IOException {
        revision = new SimpleDirectoryRevision(new SimplePath(path), commitId,
                PageUtils.createPage(nodes, summary.isLastPage(), summary.getPageRequest()));
    }

    @Override
    public boolean onTreeNode(@Nonnull ContentTreeNode node) throws IOException {
        nodes.add(node);

        return true;
    }

    @Nonnull
    public DirectoryRevision getDirectoryRevision() {
        return revision;
    }
}
