package com.jscape.inet.ssh.protocol.v2.authentication;

import com.jscape.inet.ssh.protocol.v2.marshaling.*;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.PublicKeyCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.PublicKeyCodecs;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.SignatureCodec;
import com.jscape.inet.ssh.protocol.v2.marshaling.keys.SignatureCodecs;
import com.jscape.inet.ssh.protocol.v2.messages.*;
import com.jscape.util.CollectionTools;
import com.jscape.util.io.DataCodec;

import java.security.PublicKey;
import java.util.Collection;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class PublicKeyAuthenticationMessages
        implements MessageCodec.Factory {

    public static final Class[] REQUEST_TYPES = {
            SshMsgUserAuthRequestNone.class,
            SshMsgUserAuthRequestPublicKey.class,
            SshMsgUserAuthRequestPublicKeySignature.class
    };

    private final MessageCodec.Entry[] entries;

    public static MessageCodec init(MessageCodec codec) {
        return AuthenticationMessages.init(codec.set(entries()));
    }

    public static PublicKeyAuthenticationMessages defaultMessages() {
        Collection<MessageCodec.Entry> entries = CollectionTools.collect(AuthenticationMessages.ENTRIES, entries());
        return new PublicKeyAuthenticationMessages(entries.toArray(new MessageCodec.Entry[entries.size()]));
    }

    private static MessageCodec.Entry[] entries() {
        DataCodec<PublicKey> publicKeyCodec = PublicKeyCodecs.init(new PublicKeyCodec());

        return new MessageCodec.Entry[]{
                new MessageCodec.Entry(50, new SshMsgUserAuthRequestCodec(methodEntries()), REQUEST_TYPES),
                new MessageCodec.Entry(60, new SshMsgUserAuthPkOkCodec(publicKeyCodec), SshMsgUserAuthPkOk.class)
        };
    }

    private static SshMsgUserAuthRequestCodec.Entry[] methodEntries() {
        DataCodec<PublicKey> publicKeyCodec = PublicKeyCodecs.init(new PublicKeyCodec());
        DataCodec<Signature> signatureCodec = SignatureCodecs.init(new SignatureCodec());

        return new SshMsgUserAuthRequestCodec.Entry[]{
                new SshMsgUserAuthRequestCodec.Entry("none", new SshMsgUserAuthRequestNoneCodec(), SshMsgUserAuthRequestNone.class),
                new SshMsgUserAuthRequestCodec.Entry("publickey", new SshMsgUserAuthRequestPublicKeyCodec(publicKeyCodec, signatureCodec), SshMsgUserAuthRequestPublicKey.class, SshMsgUserAuthRequestPublicKeySignature.class)
        };
    }

    public PublicKeyAuthenticationMessages(MessageCodec.Entry... entries) {
        assertNotNull(entries);
        this.entries = entries;
    }

    @Override
    public MessageCodec update(MessageCodec codec) {
        return codec.set(this.entries);
    }
}
