/*
 * 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.oscore.logging.core.provider;

import com.scytl.products.oscore.logging.api.domain.TransactionInfo;

import java.util.concurrent.ThreadLocalRandom;

/**
 * Provider for {@link TransactionInfo}. It encapsulates the creation and
 * obtention of the transaction info.
 */
public class TransactionInfoProvider {

    private static final Long MAX_TRACK_ID = 1_048_576L;

    private final ThreadLocal<TransactionInfo> trackIdThreadLocal;

    /**
     * Constructs the Track Id wrapper.
     */
    public TransactionInfoProvider() {
        trackIdThreadLocal = new ThreadLocal<>();
    }

    /**
     * Generates the track id.
     *
     * @param tenant
     * @param clientIpAddress
     * @param serverIpAddress
     * @return a new {@link TransactionInfo} object.
     */
    public TransactionInfo generate(final String tenant, final String clientIpAddress, final String serverIpAddress) {
        final Long transactionId = ThreadLocalRandom.current().nextLong(MAX_TRACK_ID);

        final TransactionInfo transactionInfo = new TransactionInfo(transactionId, tenant, clientIpAddress,
                serverIpAddress);

        set(transactionInfo);

        return transactionInfo;
    }

    /**
     * Sets the transaction info
     *
     * @param transactionInfo
     */
    public void set(final TransactionInfo transactionInfo) {

        trackIdThreadLocal.set(transactionInfo);
    }

    /**
     * Retrieves the Track Id.
     *
     * @return
     */
    public TransactionInfo get() {
        return trackIdThreadLocal.get();
    }

}
