class GroupByParser {

    public static GroupBy parse(String expr) {
        List<GroupBy.Item> items = new ArrayList<>();
        GroupBy.Item item;
        String[] names = Strings.split(expr, ',');
        for (String name : names) {
            String[] parts = Strings.splitWhitespaces(name);
            if (parts.length <= 2) {
                String[] join = Strings.split(parts[0], ".");
                if (join.length == 1) {
                    if (parts.length == 1) {
                        item = new GroupBy.Item(parts[0]);
                    } else {
                        item = new GroupBy.Item(parts[0], parts[1]);
                    }
                } else if (join.length == 2) {
                    if (parts.length == 1) {
                        item = new GroupBy.Item(join[1], null, join[0]);
                    } else {
                        item = new GroupBy.Item(join[1], parts[1], join[0]);
                    }
                } else {
                    throw new BadRequestException("Invalid join item '" + parts[0] + "'");
                }
            } else {
                throw new BadRequestException("Invalid select item '" + name + "'");
            }
            items.add(item);
        }
        return new GroupBy(items.toArray(new GroupBy.Item[items.size()]));
    }

}