package com.fitbank.common;

import com.fitbank.common.conectivity.HbSession;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

/**
 * @author Fitbank
 * @version 2.0
 */
public final class MessageIdGenerator {

    private static final MessageIdGenerator INSTANCE = new MessageIdGenerator();

    public static MessageIdGenerator getInstance() {
        return INSTANCE;
    }

    public synchronized String generateId(String pPrefix) {
        boolean openSession;
        try {
            openSession = !Helper.getSession().isOpen();
        } catch (Exception e) {
            openSession = true;
        }

        if (openSession) {
            Helper.setSession(HbSession.getInstance().openSession());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMMddHHmmssSSSSSS");
        Double d = Math.floor(Math.random() * 1000);
        DecimalFormat df = new DecimalFormat("000");
        String msg = pPrefix + sdf.format(
                ApplicationDates.getDBTimestamp()) + df.
                format(d);
        if (msg.length() > 30) {
            msg = msg.substring(msg.length() - 30);
        }

        if (openSession) {
            Helper.closeSession();
        }

        return msg;
    }

}
