/*
 * Copyright (c) 2004, ADAPT project partners (IST-2001-37126).
 */

package org.eu.adapt.demonstrator.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class UniqueIdentifierGenerator
{
    public static String createUniqueIdentifier()
    {
        if (_postfix == null)
            init();

        long currentPrefixValue = 0;
        synchronized (UniqueIdentifierGenerator.class)
        {
            currentPrefixValue = _prefixValue;
            _prefixValue++;
        }

        StringBuffer uniqueIdentifier = new StringBuffer(8 + _postfix.length());

        long remainingCurrentPrefixValue = currentPrefixValue;
        for (int count = 0; count < 8; count++)
        {
            uniqueIdentifier.append(Character.forDigit((int) (remainingCurrentPrefixValue % 16), 16));
            remainingCurrentPrefixValue = remainingCurrentPrefixValue >>> 4;
        }

        uniqueIdentifier.append(_postfix);

        return uniqueIdentifier.toString();
    }

    private static void init()
    {
        synchronized (UniqueIdentifierGenerator.class)
        {
            if (_postfix == null)
            {
                StringBuffer postfixBuffer = new StringBuffer();

                long value          = 0;
                long remainingValue = 0;

                value          = System.currentTimeMillis();
                remainingValue = value;
                for (int count = 0; count < 8; count++)
                {
                    postfixBuffer.append(Character.forDigit((int) (remainingValue % 16), 16));
                    remainingValue = remainingValue >>> 4;
                }

                try
                {
                    InetAddress localHost      = InetAddress.getLocalHost();
                    byte[]      localHostBytes = localHost.getAddress();

                    value = 256 * (256 * (256 * (256 * localHostBytes[0]) + localHostBytes[1]) + localHostBytes[2]) + localHostBytes[3];
                }
                catch (UnknownHostException unknownHostException)
                {
                    value = 0;
                }

                if (value != 0)
                {
                    remainingValue = Math.abs(value);
                    for (int count = 0; count < 8; count++)
                    {
                        postfixBuffer.append(Character.forDigit((int) (remainingValue % 16), 16));
                        remainingValue = remainingValue >>> 4;
                    }

                    _postfix = postfixBuffer.toString();
                }
            }
        }
    }

    public static long   _prefixValue = 0;
    public static String _postfix     = null;
}
