aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/connector/gc/UTFGridPosition.java
blob: f5cd208cf8cf9e07e01d47dde703e44ed804b43c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package cgeo.geocaching.connector.gc;

import cgeo.geocaching.utils.MatcherWrapper;

import java.util.regex.Pattern;


/**
 * Representation of a position inside an UTFGrid
 */
final class UTFGridPosition {

    final int x;
    final int y;
    private final static Pattern PATTERN_JSON_KEY = Pattern.compile("[^\\d]*" + "(\\d+),\\s*(\\d+)" + "[^\\d]*"); // (12, 34)

    UTFGridPosition(final int x, final int y) {
        if (x < 0 || x > UTFGrid.GRID_MAXX) {
            throw new IllegalArgumentException("x outside bounds");
        }
        if (y < 0 || y > UTFGrid.GRID_MAXY) {
            throw new IllegalArgumentException("y outside bounds");
        }
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    /**
     * @param key
     *            Key in the format (xx, xx)
     */
    static UTFGridPosition fromString(final String key) {
        final MatcherWrapper matcher = new MatcherWrapper(UTFGridPosition.PATTERN_JSON_KEY, key);
        try {
            if (matcher.matches()) {
                final int x = Integer.parseInt(matcher.group(1));
                final int y = Integer.parseInt(matcher.group(2));
                return new UTFGridPosition(x, y);
            }
        } catch (final NumberFormatException ignored) {
        }
        return new UTFGridPosition(0, 0);
    }

}