package com.atlassian.stash.internal.scm.git.pull;

import com.atlassian.bitbucket.pull.PullRequest;
import com.atlassian.bitbucket.repository.Branch;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.git.GitAgent;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;

/**
 * @since 2.9
 */
@NotThreadSafe
public class DefaultPullRequestRefs implements PullRequestRefs {

    private final GitAgent agent;
    private final String fromId;
    private final String mergeId;
    private final Repository repository;
    private final String toId;

    private Branch from;
    private Branch to;

    public DefaultPullRequestRefs(GitAgent agent, PullRequest pullRequest) {
        this.agent = agent;

        repository = pullRequest.getToRef().getRepository();

        PullRequestRefBuilder builder = PullRequestRefBuilder.darkRef().id(pullRequest);
        fromId = builder.type(PullRequestRefType.FROM).toRef();
        mergeId = builder.type(PullRequestRefType.MERGE).toRef();
        toId = builder.type(PullRequestRefType.TO).toRef();
    }

    @Nonnull
    @Override
    public String getFrom() {
        return fromId;
    }

    @Nonnull
    @Override
    public String getMerge() {
        return mergeId;
    }

    @Nonnull
    @Override
    public String getTo() {
        return toId;
    }

    @Override
    public Branch resolveFrom() {
        if (from == null) {
            from = agent.resolveBranch(repository, getFrom(), true);
        }
        return from;
    }

    @Override
    public Branch resolveTo() {
        if (to == null) {
            to = agent.resolveBranch(repository, getTo(), true);
        }
        return to;
    }
}
