/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * An type-safe enumeration class that also has an string and interger 
 * associated with each entry.
 * @author buckett
 */
abstract public class IntStringEnum
{
        private static Map enums = new HashMap();
        private int id;
        private String name;
        
        /**
         * Standard constructor.
         * @param name The name to use in ResourceBundle lookups.
         */
        protected IntStringEnum (String name, Class clazz)
        {  
            List all = getList(clazz);
            this.id = all.size();
            this.name = name;
            all.add(id, this);
        }
        
        public int getId()
        {
            return id;
        }
        
        public String getName()
        {
            return name;
        }
        
        protected static Object getConst(int id, Class clazz)
        {
            try
            {
                List all = getList(clazz);
                return all.get(id);                
            }
            catch (IndexOutOfBoundsException iooe)
            {
                return null;
            }
            
        }

        public static Object getConst(String name, Class clazz)
        {
            Iterator allIt = getList(clazz).iterator();
            while (allIt.hasNext())
            {
                IntStringEnum next = ((IntStringEnum)allIt.next());
                if (next.getName().equals(name))
                    return next;
            }
            return null;
        }

        private static List getList(Class clazz)
        {
            if (enums.containsKey(clazz))
                return (List)enums.get(clazz);
            List list = new ArrayList();
            enums.put(clazz, list);
            return list;
        }
}
