package com.atlassian.bitbucket.rest.util;

import com.atlassian.bitbucket.rest.RestMapEntity;
import com.atlassian.bitbucket.util.NamedLink;
import org.codehaus.jackson.map.annotate.JsonSerialize;

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

/**
 * An optionally-named link relating to an entity. A JSON representation of
 * {@link NamedLink}.
 */
@JsonSerialize
public class RestNamedLink extends RestMapEntity implements NamedLink {

    public static final Function<NamedLink, RestNamedLink> REST_TRANSFORM = RestNamedLink::new;

    public static final String ATTR_HREF = "href";
    public static final String ATTR_NAME = "name";

    public RestNamedLink(@Nonnull String href) {
        this(href, null);
    }

    public RestNamedLink(@Nonnull String href, @Nullable String name) {
        put(ATTR_HREF, href);
        putIfNotNull(ATTR_NAME, name);
    }

    public RestNamedLink(@Nonnull NamedLink link) {
        this(link.getHref(), link.getName());
    }

    public RestNamedLink(@Nonnull Map<String, Object> map) {
        super(map);
    }

    @Nonnull
    @Override
    public String getName() {
        return getStringProperty(ATTR_NAME);
    }

    @Nonnull
    @Override
    public String getHref() {
        return getStringProperty(ATTR_HREF);
    }

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