package com.atlassian.stash.internal.repository.sync.command;

import com.atlassian.stash.internal.repository.sync.BulkRefSyncRequest;
import com.atlassian.bitbucket.repository.RefChange;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.google.common.collect.Iterators;

import java.util.Collection;
import java.util.Iterator;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @since 2.6
 */
public abstract class AbstractRefsCommandParameters extends AbstractCommandParameters implements Iterable<RefChange> {

    protected final Collection<RefChange> refChanges;

    protected AbstractRefsCommandParameters(BulkRefSyncRequest request) {
        super(request.getRepository(), request.getUpstream(), request.getUser());

        this.refChanges = checkNotNull(request.getRefChanges(), "refChanges");
    }

    protected AbstractRefsCommandParameters(Repository repository, Repository upstream, ApplicationUser user) {
        super(repository, upstream, user);

        //This is done to ensure full synchronizations are _intentional_, not an accident caused by passing an empty
        //iterator, because full synchronizations may be significantly more expensive than incremental ones
        refChanges = null;
    }

    @Override
    public Iterator<RefChange> iterator() {
        if (refChanges == null) {
            return Iterators.emptyIterator();
        }

        return refChanges.iterator();
    }

    public int size() {
        return refChanges == null ? 0 : refChanges.size();
    }
}
