package com.atlassian.bitbucket.rest.pull;

import com.atlassian.bitbucket.pull.PullRequestRef;
import com.atlassian.bitbucket.rest.annotation.JsonSurrogate;
import com.atlassian.bitbucket.rest.RestMapEntity;
import com.atlassian.bitbucket.rest.repository.RestRepository;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Map;

@JsonSerialize
@JsonSurrogate(PullRequestRef.class)
public class RestPullRequestRef extends RestMapEntity {

    private static final String ID = "id";
    private static final String DISPLAY_ID = "displayId";
    private static final String LATEST_COMMIT = "latestCommit";
    private static final String REPOSITORY = "repository";

    public RestPullRequestRef(PullRequestRef ref) {
        this(ref.getId(), ref.getDisplayId(), ref.getLatestCommit(),
                new RestRepository(ref.getRepository(), true));
    }

    public RestPullRequestRef(String refId, String displayId, String latestCommit, RestRepository repository) {
        put(ID, refId);
        putIfNotNull(DISPLAY_ID, displayId);
        putIfNotNull(LATEST_COMMIT, latestCommit);
        put(REPOSITORY, repository);
    }

    private RestPullRequestRef(Map<String, Object> values) {
        super(values);
    }

    public RestRepository getRepository() {
        return RestRepository.valueOf(get(REPOSITORY));
    }

    @Nonnull
    public String getId() {
        return getStringProperty(ID);
    }

    @Nullable
    @SuppressWarnings("unchecked")
    public static RestPullRequestRef valueOf(@Nullable Object value) {
        if (value instanceof RestPullRequestRef) {
            return (RestPullRequestRef) value;
        } else if (value instanceof Map) {
            return new RestPullRequestRef((Map) value);
        }
        return null;
    }

    // REST Documentation Examples

    public static final RestPullRequestRef REQUEST_MASTER_EXAMPLE = new RestPullRequestRef("refs/heads/master", null,
            null, RestRepository.REQUEST_EXAMPLE_WITH_PROJECT);
    public static final RestPullRequestRef RESPONSE_MASTER_EXAMPLE = new RestPullRequestRef("refs/heads/master",
            "master", "cafebabecafebabecafebabecafebabecafebabe", RestRepository.RESPONSE_EXAMPLE);
    public static final RestPullRequestRef REQUEST_FEATURE_EXAMPLE = new RestPullRequestRef(
            "refs/heads/feature-ABC-123", null, null, RestRepository.REQUEST_EXAMPLE_WITH_PROJECT);
    public static final RestPullRequestRef RESPONSE_FEATURE_EXAMPLE = new RestPullRequestRef("refs/heads/feature",
            "feature-ABC-123", "babecafebabecafebabecafebabecafebabecafe", RestRepository.RESPONSE_EXAMPLE);

}
