package org.mercury_im.messenger.data.mapping;

import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.util.encoders.Base64;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mercury_im.messenger.data.converter.Base64PGPPublicKeyRingConverter;
import org.mercury_im.messenger.data.converter.Base64PGPSecretKeyRingConverter;
import org.pgpainless.PGPainless;
import org.pgpainless.key.collection.PGPKeyRing;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class OpenPgpKeyConverterTest {

    private static PGPKeyRing keyRing;

    @BeforeAll
    public static void before() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
        keyRing = PGPainless.generateKeyRing().simpleEcKeyRing("xmpp:alice@wonderland.lit");
    }

    @Test
    public void testPublicKeyConverter() throws IOException {
        Base64PGPPublicKeyRingConverter converter = new Base64PGPPublicKeyRingConverter();
        String expected = Base64.toBase64String(keyRing.getPublicKeys().getEncoded());

        String base64 = converter.convertToPersisted(keyRing.getPublicKeys());
        assertEquals(expected, base64);

        PGPPublicKeyRing pub = converter.convertToMapped(PGPPublicKeyRing.class, base64);
        assertEquals(keyRing.getPublicKeys().getPublicKey().getKeyID(), pub.getPublicKey().getKeyID());
    }

    @Test
    public void testSecretKeyConverter() throws IOException {
        Base64PGPSecretKeyRingConverter converter = new Base64PGPSecretKeyRingConverter();
        String expected = Base64.toBase64String(keyRing.getSecretKeys().getEncoded());

        String base64 = converter.convertToPersisted(keyRing.getSecretKeys());
        assertEquals(expected, base64);

        PGPSecretKeyRing sec = converter.convertToMapped(PGPSecretKeyRing.class, base64);
        assertEquals(keyRing.getSecretKeys().getPublicKey().getKeyID(), sec.getPublicKey().getKeyID());
    }
}
