/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.sign;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

import com.scytl.products.ov.commons.configuration.JSONSignatureConfiguration;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * Provides functionality to sign Objects which can be serialized as JSONs. The signatures are done following the
 * <em>RFC 7519</em> (https://tools.ietf.org/html/rfc7519), using the implementation of the JWT library.
 * <p>
 * Every instance of this class is to be configured with an {@link JSONSignatureConfiguration}, which is provided at the
 * constructor.
 * </p>
 */
public class JSONSigner {

	private SignatureAlgorithm algorithm;

	public JSONSigner(JSONSignatureConfiguration signatureConfiguration) {
		this.algorithm = signatureConfiguration.getAlgorithm();
	}

	/**
	 * Signs any object which can be serialized in JSON format.
	 * <p>
	 * Note that it is important that the objects that are to be signed have <em>getter</em> methods.
	 * </p>
	 */
	public String sign(PrivateKey privateKey, Object objectToSign) {

		Map<String, Object> claimMap = new HashMap<>();
		claimMap.put("objectToSign", objectToSign);

		return Jwts.builder().setClaims(claimMap).signWith(algorithm, privateKey).compact();
	}

}
