/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
package org.apache.commons.lang.enum;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * タイプセーフな enum のスーパークラスとなる抽象クラスです。
 * {@primary Abstract superclass for type-safe enums.}
 * <p>
 * C言語にあって Java に欠けている機能の一つが列挙型です。
 * int をベースにした C の実装は不十分で誤用を招きます。
 * オリジナルの Java の勧告とほとんどのJDKは int を不変の値として使用します。
 * しかしより強固でタイプセーフなクラスをベースにされた解決策がデザインされています。
 * このクラスは基本的なタイプセーフな列挙型のパターンを提供します。
 * {@primary One feature of the C programming language lacking in Java is enumerations. The
 * C implementation based on ints was poor and open to abuse. The original Java
 * recommendation and most of the JDK also uses int constants. It has been recognised
 * however that a more robust type-safe class-based solution can be designed. This
 * class follows the basic Java type-safe enumeration pattern.}
 * <p>
 * <em>注:</em> Java クラスローダの処理に依存して結果が変わるため
 * Enum オブジェクトの比較には == ではなく equals() メソッドを使う必要があります。
 * The equals() メソッドは初めに == を実行するため、たいていの場合は同じ結果になります。
 * {@primary <em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing Enum objects
 * should always be done using the equals() method, not ==. The equals() method will
 * try == first so in most cases the effect is the same.}
 * <p>
 * このクラスは継承して使用する必要があります。 例えば:
 * {@primary To use this class, it must be subclassed. For example:}
 *
 * <pre>
 * public final class ColorEnum extends Enum {
 *   public static final ColorEnum RED = new ColorEnum("Red");
 *   public static final ColorEnum GREEN = new ColorEnum("Green");
 *   public static final ColorEnum BLUE = new ColorEnum("Blue");
 *
 *   private ColorEnum(String color) {
 *     super(color);
 *   }
 * 
 *   public static ColorEnum getEnum(String color) {
 *     return (ColorEnum) getEnum(ColorEnum.class, color);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(ColorEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(ColorEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(ColorEnum.class);
 *   }
 * }
 * </pre>
 * <p>
 * 上に見られるように各 enum は名前をもっています。 これには <code>getName</code> を使用することによりアクセスできます。
 * {@primary As shown, each enum has a name. This can be accessed using <code>getName</code>.}
 * <p>
 * <code>getEnum</code> と <code>iterator</code> のメソッドの使用をお勧めします。
 * 不幸なことに、Javaの制限のために各サブクラス毎にこのようなコードが必要となってしまいます。
 * この代案は {@link EnumUtils} クラスの使用です。
 * {@primary The <code>getEnum</code> and <code>iterator</code> methods are recommended. 
 * Unfortunately, Java restrictions require these to be coded as shown in each subclass.
 * An alternative choice is to use the {@link EnumUtils} class.}
 * <p>
 * <em>注:</em> このクラスのオリジナルは Jakarta Avalon プロジェクト内にあります。
 * {@primary <em>NOTE:</em> This class originated in the Jakarta Avalon project.}
 * </p>
 *
 * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a>
 * @translator 日置 聡
 * @status firstdraft
 * @update 2003/08/05
 * @version $Id: Enum.java,v 1.1.1.1 2004/02/13 10:02:04 hioki Exp $
 */
public abstract class Enum implements Comparable, Serializable {
    /**
     * 空のマップ(JDK1.2 は空のマップを持っていないので)。
     * {@primary An empty map, as JDK1.2 didn't have an empty map}
     */
    private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap());
    /**
     * キーがクラス名、値がエントリーの Map。
     * {@primary Map, key of class name, value of Entry.}
     */
    private static final Map cEnumClasses = new HashMap();
    /**
     * Enum を表現する名称。
     * {@primary The string representation of the Enum.}
     */
    private final String iName;

    /**
     * ソースコードの順序を保持してイテレータを使用可能とします。
     * {@primary Enable the iterator to retain the source code order}
     */
    private static class Entry {
        /** Enumを名称でマップする Map。 {@primary Map of Enum name to Enum} */
        final Map map = new HashMap(50);
        /** ソースコード内の順番で格納する List。 {@primary List of Enums in source code order} */
        final List list = new ArrayList(25);

        /**
         * 制限されたコンストラクタ。
         * {@primary Restrictive constructor}
         */
        private Entry() {
        }
    }

    /**
     * 列挙型に追加する新しい名称のアイテムを生成します。
     * {@primary Constructor to add a new named item to the enumeration.}
     *
     * @param name  enum オブジェクトの名称
     * {@primary the name of the enum object}
     * @throws IllegalArgumentException 名称が null または空の文字列だった場合
     * {@primary if the name is null or a blank string}
     */
    protected Enum(String name) {
        super();
        if (name == null || name.length() == 0) {
            throw new IllegalArgumentException("The Enum name must not be empty");
        }
        iName = name;
        Entry entry = (Entry) cEnumClasses.get(getClass().getName());
        if (entry == null) {
            entry = new Entry();
            cEnumClasses.put(getClass().getName(), entry);
        }
        if (entry.map.containsKey(name)) {
            throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added");
        }
        entry.map.put(name, this);
        entry.list.add(this);
    }

    /**
     * 複数のコピーが無駄に生成される、または不正な
     * enum 型が生成される事のないようにクラスの直列化復元を処理します。
     * {@primary Handle the deserialization of the class to ensure that multiple
     * copies are not wastefully created, or illegal enum types created.}
     * @return 解決されたオブジェクト
     * {@primary the resolved object}
     */
    protected Object readResolve() {
        return Enum.getEnum(getClass(), getName());
    }

    /**
     * クラスと名称から Enum を取得します。
     * {@primary Gets an Enum object by class and name.}
     * 
     * @param enumClass  取得元となる Enum クラス
     * {@primary the class of the Enum to get}
     * @param name  Enum の名称、または null
     * {@primary the name of the Enum to get, may be null}
     * @return enum オブジェクト、該当する enum が存在しない場合には null
     * {@primary the enum object, or null if the enum does not exist}
     * @throws IllegalArgumentException enum クラスが null だった場合
     * {@primary if the enum class is null}
     */
    protected static Enum getEnum(Class enumClass, String name) {
        if (enumClass == null) {
            throw new IllegalArgumentException("The Enum Class must not be null");
        }
        Entry entry = (Entry) cEnumClasses.get(enumClass.getName());
        if (entry == null) {
            return null;
        }
        return (Enum) entry.map.get(name);
    }

    /**
     * Enum クラスの名称から Enum オブジェクトの Map を取得します。
     * 要求されたクラスが Enum オブジェクトを持っていなかった場合には空の Map を返します。
     * {@primary Gets the Map of Enum objects by name using the Enum class.
     * If the requested class has no enum objects an empty Map is returned.}
     * 
     * @param enumClass  取得元となる Enum クラス
     * {@primary enumClass  the class of the Enum to get}
     * @return enum オブジェクトの Map
     * {@primary the enum object Map}
     * @throws IllegalArgumentException enum クラスが null だった場合
     * {@primary if the enum class is null}
     * @throws IllegalArgumentException enum クラスが Enum のサブクラスでなかった場合
     * {@primary if the enum class is not a subclass of Enum}
     */
    protected static Map getEnumMap(Class enumClass) {
        if (enumClass == null) {
            throw new IllegalArgumentException("The Enum Class must not be null");
        }
        if (Enum.class.isAssignableFrom(enumClass) == false) {
            throw new IllegalArgumentException("The Class must be a subclass of Enum");
        }
        Entry entry = (Entry) cEnumClasses.get(enumClass.getName());
        if (entry == null) {
            return EMPTY_MAP;
        }
        return Collections.unmodifiableMap(entry.map);
    }

    /**
     * Enum クラスを使用して Enum オブジェクトのリストを取得します。 
     * このリスト内はオブジェクトの生成された順番に並んでいます(ソースコード内の順番)。
     * 指定されたクラスが enum オブジェクトを持っていない場合には空の List を返します。
     * {@primary Gets the List of Enum objects using the Enum class.
     * The list is in the order that the objects were created (source code order).
     * If the requested class has no enum objects an empty List is returned.}
     * 
     * @param enumClass  取得元となる Enum クラス
     * {@primary the class of the Enum to get}
     * @return enum オブジェクトの List
     * {@primary the enum object List}
     * @throws IllegalArgumentException enum クラスが null だった場合
     * {@primary if the enum class is null}
     * @throws IllegalArgumentException enum クラスが Enum のサブクラスでなかった場合
     * {@primary if the enum class is not a subclass of Enum}
     */
    protected static List getEnumList(Class enumClass) {
        if (enumClass == null) {
            throw new IllegalArgumentException("The Enum Class must not be null");
        }
        if (Enum.class.isAssignableFrom(enumClass) == false) {
            throw new IllegalArgumentException("The Class must be a subclass of Enum");
        }
        Entry entry = (Entry) cEnumClasses.get(enumClass.getName());
        if (entry == null) {
            return Collections.EMPTY_LIST;
        }
        return Collections.unmodifiableList(entry.list);
    }

    /**
     * Enum クラス内の Enum オブジェクトを走査するイテレータを取得します。.
     * このイテレータはオブジェクトの生成された順番に並んでいます(ソースコード内の順番)。
     * 指定されたクラスが enum オブジェクトを持っていない場合には空の Iterator を返します。
     * {@primary Gets an iterator over the Enum objects in an Enum class.
     * The iterator is in the order that the objects were created (source code order).
     * If the requested class has no enum objects an empty Iterator is returned.}
     * 
     * @param enumClass  取得元となる Enum クラス
     * {@primary enumClass  the class of the Enum to get}
     * @return an enum オブジェクトの イテレータ
     * {@primary an iterator of the Enum objects}
     * @throws IllegalArgumentException enum クラスが null だった場合
     * {@primary if the enum class is null}
     * @throws IllegalArgumentException enum クラスが Enum のサブクラスでなかった場合
     * {@primary if the enum class is not a subclass of Enum}
     */
    protected static Iterator iterator(Class enumClass) {
        return Enum.getEnumList(enumClass).iterator();
    }

    /**
     * コンストラクタで設定された Enum アイテムの名称を取得します。
     * {@primary Retrieve the name of this Enum item, set in the constructor.}
     * 
     * @return Enum アイテムの名称
     * {@primary the <code>String</code> name of this Enum item}
     */
    public final String getName() {
        return iName;
    }

    /**
     * 等しいかどうかのチェックを行います。
     * 2つの Enum オブジェクト の判定は、クラス名と名称が等しいかどうかにより行われます。
     * 同一であるかのチェック(==の事)が最初に行われるため、たいていの場合このメソッドは高速に動作します。
     * {@primary Tests for equality. Two Enum objects are considered equal
     * if they have the same class names and the same names.
     * Identity is tested for first, so this method usually runs fast.}
     *
     * @param other  等しいかどうかの比較対照となるオブジェクト
     * {@primary the other object to compare for equality}
     * @return Enums が等しい場合 true
     * {@primary if the Enums are equal}
     */
    public final boolean equals(Object other) {
        if (other == this) {
            return true;
        } else if (other == null) {
            return false;
        } else if (other.getClass() == this.getClass()) {
            // shouldn't happen, but...
            return iName.equals(((Enum) other).iName);
        } else if (other.getClass().getName().equals(this.getClass().getName())) {
            // different classloaders
            try {
                // try to avoid reflection
                return iName.equals(((Enum) other).iName);

            } catch (ClassCastException ex) {
                // use reflection
                try {
                    Method mth = other.getClass().getMethod("getName", null);
                    String name = (String) mth.invoke(other, null);
                    return iName.equals(name);
                } catch (NoSuchMethodException ex2) {
                    // ignore - should never happen
                } catch (IllegalAccessException ex2) {
                    // ignore - should never happen
                } catch (InvocationTargetException ex2) {
                    // ignore - should never happen
                }
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 適切な列挙型のハッシュコードを返します。
     * {@primary Returns a suitable hashCode for the enumeration.}
     *
     * @return 名称をベースとするハッシュコード
     * {@primary a hashcode based on the name}
     */
    public final int hashCode() {
        return 7 + iName.hashCode();
    }

    /**
     * 順序をチェックします。 
     * デフォルトの順番は名称のアルファベット順となりますが、これはサブクラスによってオーバライドされます。
     * {@primary Tests for order. The default ordering is alphabetic by name, but this
     * can be overridden by subclasses.}
     * 
     * @see java.lang.Comparable#compareTo(Object)
     * @param other  比較対照となるオブジェクト
     * {@primary the other object to compare to}
     * @return 比較対照より小さかった場合 -ve(マイナス)、比較対照より大きかった場合 +ve(プラス)、等しかった場合 0
     * {@primary -ve if this is less than the other object, +ve if greater than, 0 of equal}
     * @throws ClassCastException 比較対照が Enum でなかった場合
     * {@primary if other is not an Enum}
     * @throws NullPointerException 比較対照が null だった場合
     * {@primary if other is null}
     */
    public int compareTo(Object other) {
        return iName.compareTo(((Enum) other).iName);
    }

    /**
     * Enum アイテムを読みやすい形で返します。 デバッグの際に使用されます。
     * {@primary Human readable description of this Enum item. For use when debugging.}
     * 
     * @return <code>type[name]</code> のフォームの文字列、例:
     * <code>Color[Red]</code>、 注 型の名前の中のパッケージ名は省略されます。
     * {@primary String in the form <code>type[name]</code>, for example:
     * <code>Color[Red]</code>. Note that the package name is stripped from
     * the type name.}
     */
    public String toString() {
        String shortName = getClass().getName();
        int pos = shortName.lastIndexOf('.');
        if (pos != -1) {
            shortName = shortName.substring(pos + 1);
        }
        return shortName + "[" + getName() + "]";
    }
}
