aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/connector/gc/UTFGridPosition.java
blob: eff193aff4f07e4688df11095f7f993cde1a589c (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
54
package cgeo.geocaching.connector.gc;

import cgeo.geocaching.utils.MatcherWrapper;

import java.util.regex.Pattern;


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

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

    public 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)
     * @return
     */
    static UTFGridPosition fromString(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 (NumberFormatException e) {
        }
        return new UTFGridPosition(0, 0);
    }

}