/*
 * Copyright (C) 2021 Veli Tasalı
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package org.monora.uprotocol.client.android.database

import android.util.Base64
import androidx.room.TypeConverter
import org.monora.uprotocol.core.protocol.ClientType
import org.spongycastle.cert.X509CertificateHolder
import org.spongycastle.cert.jcajce.JcaX509CertificateConverter
import org.spongycastle.jce.provider.BouncyCastleProvider
import java.security.cert.X509Certificate

class ClientTypeConverter {
    private val bouncyCastleProvider = BouncyCastleProvider()

    @TypeConverter
    fun fromCertificate(value: X509Certificate?): String? {
        if (value == null)
            return null
        return Base64.encodeToString(value.encoded, Base64.DEFAULT)
    }

    @TypeConverter
    fun toCertificate(value: String?): X509Certificate? {
        if (value == null)
            return null

        return JcaX509CertificateConverter().setProvider(bouncyCastleProvider)
            .getCertificate(X509CertificateHolder(Base64.decode(value, Base64.DEFAULT)))
    }

    @TypeConverter
    fun fromType(value: ClientType): String = value.protocolValue

    @TypeConverter
    fun toType(value: String): ClientType = ClientType.from(value)
}