package org.jivesoftware.smackx.ikey;

import org.bouncycastle.util.encoders.Base64;
import org.jivesoftware.smackx.ikey.element.IkeyElement;
import org.jivesoftware.smackx.ikey.mechanism.IkeySignatureVerificationMechanism;
import org.jxmpp.jid.EntityBareJid;

import java.io.IOException;

public class IkeySignatureVerifier {

    private final IkeySignatureVerificationMechanism signatureVerificationMechanism;

    public IkeySignatureVerifier(IkeySignatureVerificationMechanism signatureVerificationMechanism) {
        this.signatureVerificationMechanism = signatureVerificationMechanism;
    }

    public boolean verify(IkeyElement element, EntityBareJid owner)
            throws IOException {
        throwIfMismatchingMechanism(element);
        throwIfMismatchingOwnerJid(element, owner);

        byte[] utf8 = element.getSignedElement().getUtf8Bytes();
        byte[] signature = Base64.decode(element.getProof().getBase64Signature());

        return signatureVerificationMechanism.isSignatureValid(utf8, signature);
    }

    private static void throwIfMismatchingOwnerJid(IkeyElement element, EntityBareJid owner) {
        if (!element.getSignedElement().getChildElement().getJid().equals(owner)) {
            throw new IllegalArgumentException("Provided ikey element does not contain jid of " + owner);
        }
    }

    private void throwIfMismatchingMechanism(IkeyElement element) {
        if (element.getType() != signatureVerificationMechanism.getType()) {
            throw new IllegalArgumentException("Element was created using mechanism " + element.getType() +
                    " but this is a verifier for " + signatureVerificationMechanism.getType() + " ikey elements.");
        }
    }
}
