1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.chimpchat.core;
18
19import com.android.chimpchat.ChimpManager;
20
21import com.google.common.collect.Lists;
22
23import java.io.IOException;
24import java.util.ArrayList;
25import java.util.Arrays;
26import java.util.Collection;
27import java.util.Collections;
28import java.util.List;
29import java.util.logging.Level;
30import java.util.logging.Logger;
31
32/** A class for selecting objects by their text */
33public class MultiSelectorText implements IMultiSelector {
34    private static final Logger LOG = Logger.getLogger(ChimpView.class.getName());
35    private String text;
36
37    /**
38     * @param text the text which to select objects by
39     */
40    public MultiSelectorText(String text) {
41        this.text = text;
42    }
43
44    /**
45     * A method for selecting views by the given text.
46     * @return The collection of views that contain the given text
47     */
48    public Collection<IChimpView> getViews(ChimpManager manager) {
49        String response;
50        List<String> ids;
51        try {
52            response = manager.getViewsWithText(text);
53            ids = Arrays.asList(response.split(" "));
54        } catch (IOException e) {
55            LOG.log(Level.SEVERE, "Error communicating with device: " + e.getMessage());
56            return new ArrayList<IChimpView>();
57        }
58        /* We make sure this has an even number of results because we don't necessarily know how
59         * many views with the given textthere are, but we know all of the views will return a pair
60         * of accessibility ids */
61        if (ids.size() % 2 == 0) {
62            List<IChimpView> views = new ArrayList<IChimpView>();
63            for (int i = 0; i < ids.size()/2; i++) {
64                List<String> accessibilityIds =
65                        Lists.newArrayList(ids.get(2 * i ), ids.get(2 * i + 1));
66                ChimpView view = new ChimpView(ChimpView.ACCESSIBILITY_IDS, accessibilityIds);
67                view.setManager(manager);
68                views.add(view);
69            }
70            return views;
71        }
72        LOG.log(Level.SEVERE, "Error retrieving views: " + response);
73        return Collections.emptyList();
74    }
75}
76