package com.atlassian.bitbucket.rest.util;

import com.atlassian.bitbucket.rest.RestMapEntity;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.util.Collection;
import java.util.Map;

/**
 * Represents multiple collections of links where links in each collection are related by some concept.
 */
@JsonSerialize
public class RestRelatedLinks extends RestMapEntity {
    public static final String RELATIONSHIP_SELF = "self";
    public static final String RELATIONSHIP_CLONE = "clone";

    private RestRelatedLinks(Map<String, Collection<RestNamedLink>> relations) {
        super(relations);
    }

    public static class Builder {
        private Map<String, Collection<RestNamedLink>> relatedLinks = Maps.newHashMap();

        public Builder addRelatedLinks(String relationship, Collection<RestNamedLink> links) {
            Collection<RestNamedLink> existing = relatedLinks.get(relationship);
            if (existing == null) {
                existing = Sets.newHashSet();
                relatedLinks.put(relationship, existing);
            }
            existing.addAll(links);

            return this;
        }

        public Builder addRelatedLink(String relationship, RestNamedLink link) {
            Collection<RestNamedLink> existing = relatedLinks.get(relationship);
            if (existing == null) {
                existing = Sets.newHashSet();
                relatedLinks.put(relationship, existing);
            }
            existing.add(link);

            return this;
        }

        public RestRelatedLinks build() {
            return new RestRelatedLinks(relatedLinks);
        }
    }
}
