
package org.stroque.util;

import org.apache.torque.TorqueException;
import org.apache.torque.om.*;

/**
 * @author Mathieu Frenette
 * @version 1.0
 */
public class KeyHelper
{
    public static String convertObjectKeyToString(ObjectKey key)
    {
        // Determine correct prefix
        String prefix;
        if (key instanceof NumberKey)
        {
            prefix = "n";
        }
        else if (key instanceof StringKey)
        {
            prefix = "s";
        }
        else if (key instanceof ComboKey)
        {
            prefix = "c";
        }
        else
        {
            throw new UnsupportedOperationException("Unsupported ObjectKey sub-class: " + key.getClass().getName());
        }

        return prefix + key.toString();
    }

    public static ObjectKey convertStringToObjectKey(String str)
    {
        if (str == null)
        {
            return null;
        }

        try
        {
            String prefix = str.substring(0, 1);
            String key = str.substring(1);

            if (prefix.equals("n"))
            {
                return new NumberKey(key);
            }
            else if (prefix.equals("s"))
            {
                return new StringKey(key);
            }
            else if (prefix.equals("c"))
            {
                return new ComboKey(key);
            }
            else
            {
                throw new UnsupportedOperationException("Illegal prefix: " + prefix);
            }
        }
        catch (TorqueException e)
        {
            e.printStackTrace();
            throw new IllegalStateException("Couldn't create key from string: '" + str + "'.  See stack trace in console");
        }
    }
}

