package com.atlassian.stash.internal.web.soy;

import com.atlassian.plugin.spring.AvailableToPlugins;
import com.atlassian.soy.renderer.SoyDataMapper;
import com.atlassian.bitbucket.cluster.ClusterNode;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Map;

/**
 * A custom data mapper for {@link ClusterNode ClusterNodes} which generates a string representation of a node.
 *
 * @since 3.5
 */
@Component
@AvailableToPlugins(SoyDataMapper.class)
public class ClusterNodeDataMapper implements SoyDataMapper<ClusterNode, Map<String, Object>> {

    @Override
    public String getName() {
        return "ClusterNode";
    }

    @Override
    public Map<String, Object> convert(ClusterNode clusterNode) {
        return ImmutableMap.<String, Object>builder()
                .put("address", toString(clusterNode.getAddress()))
                .put("id", clusterNode.getId())
                .put("local", clusterNode.isLocal())
                .put("name", clusterNode.getName())
                .build();
    }

    private String toString(InetSocketAddress address) {
        String addressAsString = address.getHostString();
        addressAsString = addressAsString == null ? "<unknown>" : addressAsString;
        return addressAsString + ":" + address.getPort();
    }
}
