summaryrefslogtreecommitdiff
path: root/InCallUI/src/com/android/incallui/InCallContactInteractions.java
blob: 21660cbce46179d3a616379c09742f559ccf4f63 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.incallui;

import com.google.common.annotations.VisibleForTesting;

import android.content.Context;
import android.location.Address;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Wrapper class for objects that are used in generating the context about the contact in the InCall
 * screen.
 *
 * This handles generating the appropriate resource for the ListAdapter based on whether the contact
 * is a business contact or not and logic for the manipulation of data for the call context.
 */
public class InCallContactInteractions {
    private static final String TAG = InCallContactInteractions.class.getSimpleName();
    private Context mContext;
    private InCallContactInteractionsListAdapter mListAdapter;
    private boolean mIsBusiness;
    private View mBusinessHeaderView;
    private LayoutInflater mInflater;

    public InCallContactInteractions(Context context, boolean isBusiness) {
        mContext = context;
        mInflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        switchContactType(isBusiness);
    }

    public InCallContactInteractionsListAdapter getListAdapter() {
        return mListAdapter;
    }

    /**
     * Switches the "isBusiness" value, if applicable. Recreates the list adapter with the resource
     * corresponding to the new isBusiness value if the "isBusiness" value is switched.
     *
     * @param isBusiness Whether or not the contact is a business.
     *
     * @return {@code true} if a new list adapter was created, {@code} otherwise.
     */
    public boolean switchContactType(boolean isBusiness) {
        if (mIsBusiness != isBusiness || mListAdapter == null) {
            mIsBusiness = isBusiness;
            mListAdapter = new InCallContactInteractionsListAdapter(mContext,
                    mIsBusiness ? R.layout.business_context_info_list_item
                            : R.layout.person_context_info_list_item);
            return true;
        }
        return false;
    }

    public View getBusinessListHeaderView() {
        if (mBusinessHeaderView == null) {
            mBusinessHeaderView = mInflater.inflate(
                    R.layout.business_contact_context_list_header, null);
        }
        return mBusinessHeaderView;
    }

    public void setBusinessInfo(Address address, float distance,
            Pair<String, String> openingHours) {
        mListAdapter.clear();
        List<ContactContextInfo> info = new ArrayList<ContactContextInfo>();

        // Hours of operation
        if (openingHours != null) {
            BusinessContextInfo hoursInfo = constructHoursInfo(openingHours);
            if (hoursInfo != null) {
                info.add(hoursInfo);
            }
        }

        // Location information
        if (address != null) {
            BusinessContextInfo locationInfo = constructLocationInfo(address, distance);
            info.add(locationInfo);
        }

        mListAdapter.addAll(info);
    }

    /**
     * Construct a BusinessContextInfo object containing hours of operation information.
     * The format is:
     *      [Open now/Closed now]
     *      [Hours]
     *
     * @param openingHours
     * @return BusinessContextInfo object with the schedule icon, the heading set to whether the
     * business is open or not and the details set to the hours of operation.
     */
    private BusinessContextInfo constructHoursInfo(Pair<String, String> openingHours) {
        return constructHoursInfo(Calendar.getInstance(), openingHours);
    }

    /**
     * Pass in arbitrary current calendar time.
     */
    @VisibleForTesting
    BusinessContextInfo constructHoursInfo(Calendar currentTime,
            Pair<String, String> openingHours) {
        BusinessContextInfo hoursInfo = new BusinessContextInfo();
        hoursInfo.iconId = R.drawable.ic_schedule_white_24dp;

        // Note: the date of these {@link Date}s are set to January 1, 1970. The object is just
        // used as a storage for the time.
        Date openingDateTime = getSimpleDateTime(openingHours.first);
        Date closingDateTime = getSimpleDateTime(openingHours.second);

        if (openingDateTime == null || closingDateTime == null) {
            return null;
        }

        hoursInfo.heading = isOpen(openingDateTime, closingDateTime, currentTime)
                ? mContext.getString(R.string.open_now) : mContext.getString(R.string.closed_now);

        hoursInfo.detail = mContext.getString(
                R.string.opening_hours,
                DateFormat.getTimeFormat(mContext).format(openingDateTime),
                DateFormat.getTimeFormat(mContext).format(closingDateTime));
        return hoursInfo;
    }

    /**
     * Construct a BusinessContextInfo object with the location information of the business.
     * The format is:
     *      [Straight line distance in miles or kilometers]
     *      [Address without state/country/etc.]
     *
     * @param address An Address object containing address details of the business
     * @param distance The distance to the location in meters
     * @return A BusinessContextInfo object with the location icon, the heading as the distance to
     * the business and the details containing the address.
     */
    private BusinessContextInfo constructLocationInfo(Address address, float distance) {
        return constructLocationInfo(Locale.getDefault(), address, distance);
    }

    @VisibleForTesting
    BusinessContextInfo constructLocationInfo(Locale locale, Address address,
            float distance) {
        if (address == null) {
            return null;
        }

        BusinessContextInfo locationInfo = new BusinessContextInfo();
        locationInfo.iconId = R.drawable.ic_location_on_white_24dp;
        if (distance != DistanceHelper.DISTANCE_NOT_FOUND) {
            //TODO: add a setting to allow the user to select "KM" or "MI" as their distance units.
            if (Locale.US.equals(locale)) {
                locationInfo.heading = mContext.getString(R.string.distance_imperial_away,
                        distance * DistanceHelper.MILES_PER_METER);
            } else {
                locationInfo.heading = mContext.getString(R.string.distance_metric_away,
                        distance * DistanceHelper.KILOMETERS_PER_METER);
            }
        }
        if (address.getLocality() != null) {
            locationInfo.detail = mContext.getString(
                    R.string.display_address,
                    address.getAddressLine(0),
                    address.getLocality());
        } else {
            locationInfo.detail = address.getAddressLine(0);
        }
        return locationInfo;
    }

    /**
     * Get a {@link Date} object corresponding to a particular time.
     *
     * @param time A string containing a time in the format "hhmm".
     * @return A {@link Date} object with the time set to the parsed value of the "time" parameter
     * and the date set to January 1, 1970. Or {@code null} if the input string is not able to be
     * parsed.
     */
    private Date getSimpleDateTime(String time) {
        try {
            return new SimpleDateFormat("hhmm").parse(time);
        } catch (ParseException e) {
            Log.w(TAG, "Could not parse time string " + time);
        }
        return null;
    }

    /**
     * Check whether the current time falls between the opening time and the closing time.
     *
     * @param openingTime A {@link Date} object with the time set to the opening time and the date
     * set to January 1, 1970.
     * @param closingTime A {@link Date} object with the time set to the closing time and the date
     * set to January 1, 1970.
     * @param currentDateTime A {@link Calendar} object with the current date and time.
     * @return {@code true} if the current time falls within the opening and closing time bounds and
     * {@code false} otherwise.
     */
    private boolean isOpen(Date openingTime, Date closingTime, Calendar currentDateTime) {
        Calendar openTimeCalendar = Calendar.getInstance();
        openTimeCalendar.setTime(openingTime);

        Calendar closeTimeCalendar = Calendar.getInstance();
        closeTimeCalendar.setTime(closingTime);

        if (openTimeCalendar.compareTo(closeTimeCalendar) >= 0) {
            // If the open time is the same or after the close time, add a day to the close time
            // calendar.
            closeTimeCalendar.add(Calendar.DATE, 1);
        }

        // Since the date doesn't actually matter, it's easier to set the current date to the
        // opening date rather than change both the calendars for the open time and the close time.
        currentDateTime.set(
                openTimeCalendar.get(Calendar.YEAR),
                openTimeCalendar.get(Calendar.MONTH),
                openTimeCalendar.get(Calendar.DATE));

        return currentDateTime.after(openTimeCalendar) && currentDateTime.before(closeTimeCalendar);
    }

    /**
     * Get the appropriate title for the context.
     * @return The "Business info" title for a business contact and the "Recent messages" title for
     *         personal contacts.
     */
    public String getContactContextTitle() {
        return mIsBusiness
                ? mContext.getResources().getString(R.string.business_contact_context_title)
                : mContext.getResources().getString(R.string.person_contact_context_title);
    }

    public static abstract class ContactContextInfo {
        public abstract void bindView(View listItem);
    }

    public static class BusinessContextInfo extends ContactContextInfo {
        int iconId;
        String heading;
        String detail;

        @Override
        public void bindView(View listItem) {
            ImageView imageView = (ImageView) listItem.findViewById(R.id.icon);
            TextView headingTextView = (TextView) listItem.findViewById(R.id.heading);
            TextView detailTextView = (TextView) listItem.findViewById(R.id.detail);

            if (this.iconId == 0 || (this.heading == null && this.detail == null)) {
                return;
            }

            imageView.setImageDrawable(listItem.getContext().getDrawable(this.iconId));

            headingTextView.setText(this.heading);
            headingTextView.setVisibility(TextUtils.isEmpty(this.heading)
                    ? View.GONE : View.VISIBLE);

            detailTextView.setText(this.detail);
            detailTextView.setVisibility(TextUtils.isEmpty(this.detail)
                    ? View.GONE : View.VISIBLE);

        }
    }

    public static class PersonContextInfo extends ContactContextInfo {
        boolean isIncoming;
        String message;
        String detail;

        @Override
        public void bindView(View listItem) {
            TextView messageTextView = (TextView) listItem.findViewById(R.id.message);
            TextView detailTextView = (TextView) listItem.findViewById(R.id.detail);

            if (this.message == null || this.detail == null) {
                return;
            }

            messageTextView.setBackgroundResource(this.isIncoming ?
                    R.drawable.incoming_sms_background : R.drawable.outgoing_sms_background);
            messageTextView.setText(this.message);
            LayoutParams messageLayoutParams = (LayoutParams) messageTextView.getLayoutParams();
            messageLayoutParams.addRule(this.isIncoming?
                    RelativeLayout.ALIGN_PARENT_START : RelativeLayout.ALIGN_PARENT_END);
            messageTextView.setLayoutParams(messageLayoutParams);

            LayoutParams detailLayoutParams = (LayoutParams) detailTextView.getLayoutParams();
            detailLayoutParams.addRule(this.isIncoming ?
                    RelativeLayout.ALIGN_PARENT_START : RelativeLayout.ALIGN_PARENT_END);
            detailTextView.setLayoutParams(detailLayoutParams);
            detailTextView.setText(this.detail);
        }
    }

    /**
     * A list adapter for call context information. We use the same adapter for both business and
     * contact context.
     */
    private class InCallContactInteractionsListAdapter extends ArrayAdapter<ContactContextInfo> {
        // The resource id of the list item layout.
        int mResId;

        public InCallContactInteractionsListAdapter(Context context, int resource) {
            super(context, resource);
            mResId = resource;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View listItem = mInflater.inflate(mResId, null);
            ContactContextInfo item = getItem(position);

            if (item == null) {
                return listItem;
            }

            item.bindView(listItem);
            return listItem;
        }
    }
}