package org.mercury_im.messenger.data.converter;

import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.util.encoders.Base64;
import org.pgpainless.PGPainless;

import java.nio.charset.StandardCharsets;

import javax.annotation.Nullable;

import io.requery.Converter;
import lombok.SneakyThrows;

public class Base64PGPSecretKeyRingConverter implements Converter<PGPSecretKeyRing, String> {
    @Override
    public Class<PGPSecretKeyRing> getMappedType() {
        return PGPSecretKeyRing.class;
    }

    @Override
    public Class<String> getPersistedType() {
        return String.class;
    }

    @Nullable
    @Override
    public Integer getPersistedSize() {
        return null;
    }

    @SneakyThrows
    @Override
    public String convertToPersisted(PGPSecretKeyRing value) {
        if (value == null) {
            return null;
        }
        return new String(Base64.encode(value.getEncoded()), StandardCharsets.UTF_8);
    }

    @SneakyThrows
    @Override
    public PGPSecretKeyRing convertToMapped(Class<? extends PGPSecretKeyRing> type, @Nullable String value) {
        if (value == null) {
            return null;
        }
        return PGPainless.readKeyRing().secretKeyRing(Base64.decode(value.getBytes(StandardCharsets.UTF_8)));
    }
}
