package com.atlassian.bitbucket.internal.ssh.server;

import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

/**
 * Value class for describing the {@link com.atlassian.bitbucket.ssh.SshKey SshKey} that match the public key that
 * allowed SSH authentications.
 */
public class SshKeyDetails {
    private String id;
    private String label;

    public SshKeyDetails(String id, String label) {
        this.id = id;
        this.label = label;
    }

    public String getId() {
        return id;
    }

    public String getLabel() {
        return label;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("id", id)
                .add("label", label)
                .toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        SshKeyDetails that = (SshKeyDetails) o;
        return Objects.equal(id, that.id) &&
                Objects.equal(label, that.label);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id, label);
    }

    public static SshKeyDetails getFromMDC() {
        return new SshKeyDetails(MDC.get("ssh:id"), MDC.get("ssh:label"));
    }

    public void putInMDC() {
        putInMDCIfNotEmpty("ssh:id", id);
        putInMDCIfNotEmpty("ssh:label", label);
    }

    private static void putInMDCIfNotEmpty(String key, String value) {
        if (StringUtils.isNotEmpty(value)) {
            MDC.put(key, value);
        }
    }
}
