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

import com.atlassian.bitbucket.rest.RestMapEntity;
import com.atlassian.bitbucket.rest.util.RestPage;
import com.atlassian.bitbucket.ssh.SshKey;
import org.codehaus.jackson.map.annotate.JsonSerialize;

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

import static com.atlassian.bitbucket.rest.util.RestDocUtils.pageOf;

@JsonSerialize
public class RestSshKey extends RestMapEntity {

    private static final String ID = "id";
    private static final String TEXT = "text";
    private static final String LABEL = "label";

    // default ctor for jersey
    public RestSshKey() {
    }

    public RestSshKey(SshKey sshKey) {
        this(sshKey.getId(), sshKey.getText(), sshKey.getLabel());
    }

    public RestSshKey(Integer id, String text, String label) {
        putIfNotNull(ID, id);
        putIfNotNull(TEXT, text);
        putIfNotNull(LABEL, label);
    }

    private RestSshKey(Map<String, Object> map) {
        super(map);
    }

    public Integer getId() {
        return getIntProperty(ID);
    }

    public String getText() {
        return getStringProperty(TEXT);
    }

    public String getLabel() {
        return getStringProperty(LABEL);
    }

    public static final Function<SshKey, RestSshKey> REST_TRANSFORM = RestSshKey::new;

    public static final RestSshKey EXAMPLE_REQUEST = new RestSshKey(null, "ssh-rsa AAAAB3... me@127.0.0.1", null);

    public static final RestSshKey EXAMPLE_RESPONSE = new RestSshKey(1, "ssh-rsa AAAAB3... me@127.0.0.1", "me@127.0.0.1");
    public static final RestPage<RestSshKey> EXAMPLE_PAGE = pageOf(EXAMPLE_RESPONSE);

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