package com.atlassian.bitbucket.internal.mirroring.mirror.auth.ssh;

import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.ApplicationUserVisitor;
import com.atlassian.bitbucket.user.UserType;

import javax.annotation.Nonnull;

class PublicKeyUser implements ApplicationUser {

    private final String key;
    private final String keyStub;

    PublicKeyUser(String key) {
        this.key = key;
        // This will make the first few characters of the PK show up in the mirror's audit logs. This is mostly a
        // compromise to have _some_ accountability, without compromising privacy in Bitbucket Cloud's API.
        keyStub = toStub(key);
    }

    @Override
    public <T> T accept(@Nonnull ApplicationUserVisitor<T> visitor) {
        return visitor.visit(this);
    }

    @Nonnull
    @Override
    public String getDisplayName() {
        return keyStub;
    }

    @Override
    public int getId() {
        return 0;
    }

    @Nonnull
    @Override
    public UserType getType() {
        return UserType.NORMAL;
    }

    @Override
    public boolean isActive() {
        return true;
    }

    @Nonnull
    @Override
    public String getSlug() {
        return keyStub;
    }

    @Override
    public String getEmailAddress() {
        return null;
    }

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

    @Nonnull
    public String getPublicKey() {
        return key;
    }

    private String toStub(String key) {
        String[] keyArr = key.split(" ");
        if (keyArr.length < 2) {
            throw new IllegalArgumentException("Key is not an OpenSSH key.");
        }
        return keyArr[1].substring(0, Math.min(8, keyArr[1].length()));
    }
}