package ru.yandex.webmaster3.storage.notifications;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/*
 * @author leonidrom
 */
public class EmailTrackingInfoSigner {
    private static final String KEY_STRING = "4c763b4c8c19d3d1f6aacafeb7ed39e5";
    private byte[] key;

    private ThreadLocal<MessageDigest> digests = ThreadLocal.withInitial(() -> {
        try {
            return MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Unable to get MessageDigest", e);
        }
    });

    public void init() throws Exception {
        key = Hex.decodeHex(KEY_STRING.toCharArray());
    }

    public String getDigest(EmailTrackingInfo info) {
        MessageDigest digest = digests.get();
        digest.update(key);
        info.getDataAsBytes().forEach(digest::update);

        return Hex.encodeHexString(digest.digest());
    }
}
