001package ball.game.crossword;
002/*-
003 * ##########################################################################
004 * Game Applications and Utilities
005 * $Id: Label.java 5285 2020-02-05 04:23:21Z ball $
006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-game/trunk/src/main/java/ball/game/crossword/Label.java $
007 * %%
008 * Copyright (C) 2010 - 2020 Allen D. Ball
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * ##########################################################################
022 */
023import java.util.Comparator;
024import java.util.Objects;
025
026/**
027 * Crossword clue {@link Label}.
028 *
029 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
030 * @version $Revision: 5285 $
031 */
032public class Label implements Comparable<Label> {
033    private static final Comparator<? super Label> COMPARATOR =
034        Comparator
035        .<Label>comparingInt(t -> t.direction.ordinal())
036        .thenComparingInt(Label::getIndex);
037
038    private final Direction direction;
039    private final int index;
040
041    /**
042     * @param   direction       The solution word {@link Direction}.
043     * @param   index           The starting block index.
044     */
045    protected Label(Direction direction, int index) {
046        this.direction = Objects.requireNonNull(direction);
047        this.index = index;
048    }
049
050    public Direction getDirection() { return direction; }
051
052    public int getIndex() { return index; }
053
054    @Override
055    public int compareTo(Label that) {
056        return Objects.compare(this, that, COMPARATOR);
057    }
058
059    @Override
060    public boolean equals(Object object) {
061        return ((object instanceof Label)
062                ? (this.compareTo((Label) object) == 0)
063                : super.equals(object));
064    }
065
066    @Override
067    public int hashCode() { return Objects.hash(direction, index); }
068
069    @Override
070    public String toString() {
071        return (getDirection().toString().substring(0, 1)
072                + String.valueOf(index));
073    }
074
075    public static Label parse(String string) {
076        return new Label(Direction.parse(string.substring(0, 1)),
077                         Integer.parseInt(string.substring(1)));
078    }
079}