001/* [{
002Copyright 2007, 2008 Nicolas Carranza <nicarran at gmail.com>
003
004This file is part of jpen.
005
006jpen is free software: you can redistribute it and/or modify
007it under the terms of the GNU Lesser General Public License as published by
008the Free Software Foundation, either version 3 of the License,
009or (at your option) any later version.
010
011jpen is distributed in the hope that it will be useful,
012but WITHOUT ANY WARRANTY; without even the implied warranty of
013MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014GNU Lesser General Public License for more details.
015
016You should have received a copy of the GNU Lesser General Public License
017along with jpen.  If not, see <http://www.gnu.org/licenses/>.
018}] */
019package jpen;
020
021import java.util.ArrayList;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.List;
025
026public abstract class TypedClass<T extends Enum<T>>
027        implements java.io.Serializable {
028        public static final long serialVersionUID=1l;
029        public final int typeNumber;
030
031        TypedClass(int typeNumber) {
032                if(typeNumber<0)
033                        throw new IllegalArgumentException();
034                this.typeNumber=typeNumber;
035        }
036
037        abstract List<T> getAllTypes();
038
039        /**
040        @return The enum type matching the {@link #typeNumber}.
041        */
042        public final T getType() {
043                return getType(typeNumber);
044        }
045
046        private final T getType(int typeNumber){
047                List<T>allTypes=getAllTypes();
048                int customTypeOrdinal=getCustomTypeOrdinal(allTypes);
049                return allTypes.get( typeNumber < customTypeOrdinal ? typeNumber: customTypeOrdinal );
050        }
051
052        private static final <T extends Enum<T>> int getCustomTypeOrdinal(List<T> allTypes){
053                return allTypes.size()-1;// the last is always the CUSTOM
054        }
055
056        @SuppressWarnings("unchecked")
057        static final <T extends Enum<T>> List<T> createStandardTypes(List<T> allTypes){
058                int customTypeOrdinal=getCustomTypeOrdinal(allTypes);
059                List<T> stdTypes=new ArrayList<T>(customTypeOrdinal);
060                for(int i=0; i<customTypeOrdinal; i++)
061                        stdTypes.add(allTypes.get(i));
062                return Collections.unmodifiableList(stdTypes);
063        }
064
065        @Override
066        public String toString() {
067                return "(type="+getType()+")";
068        }
069}