summaryrefslogtreecommitdiff
path: root/InCallUI/src/com/android/incallui/InCallContactInteractions.java
blob: 88070fe379283f81821951ed64f31616ad8f5166 (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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
 * 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 com.android.dialer.R;

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,
            List<Pair<Calendar, Calendar>> 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(List<Pair<Calendar, Calendar>> openingHours) {
        try {
            return constructHoursInfo(Calendar.getInstance(), openingHours);
        } catch (Exception e) {
            // Catch all exceptions here because we don't want any crashes if something goes wrong.
            Log.e(TAG, "Error constructing hours info: ", e);
        }
        return null;
    }

    /**
     * Pass in arbitrary current calendar time.
     */
    @VisibleForTesting
    BusinessContextInfo constructHoursInfo(Calendar currentTime,
            List<Pair<Calendar, Calendar>> openingHours) {
        if (currentTime == null || openingHours == null || openingHours.size() == 0) {
            return null;
        }

        BusinessContextInfo hoursInfo = new BusinessContextInfo();
        hoursInfo.iconId = R.drawable.ic_schedule_white_24dp;

        boolean isOpenNow = false;
        // This variable records which interval the current time is after. 0 denotes none of the
        // intervals, 1 after the first interval, etc. It is also the index of the interval the
        // current time is in (if open) or the next interval (if closed).
        int afterInterval = 0;
        // This variable counts the number of time intervals in today's opening hours.
        int todaysIntervalCount = 0;

        for (Pair<Calendar, Calendar> hours : openingHours) {
            if (hours.first.compareTo(currentTime) <= 0
                    && currentTime.compareTo(hours.second) < 0) {
                // If the current time is on or after the opening time and strictly before the
                // closing time, then this business is open.
                isOpenNow = true;
            }

            if (currentTime.get(Calendar.DAY_OF_YEAR) == hours.first.get(Calendar.DAY_OF_YEAR)) {
                todaysIntervalCount += 1;
            }

            if (currentTime.compareTo(hours.second) > 0) {
                // This assumes that the list of intervals is sorted by time.
                afterInterval += 1;
            }
        }

        hoursInfo.heading = isOpenNow ? mContext.getString(R.string.open_now)
                : mContext.getString(R.string.closed_now);

        /*
         * The following logic determines what to display in various cases for hours of operation.
         *
         * - Display all intervals if open now and number of intervals is <=2.
         * - Display next closing time if open now and number of intervals is >2.
         * - Display next opening time if currently closed but opens later today.
         * - Display last time it closed today if closed now and tomorrow's hours are unknown.
         * - Display tomorrow's first open time if closed today and tomorrow's hours are known.
         *
         * NOTE: The logic below assumes that the intervals are sorted by ascending time. Possible
         * TODO to modify the logic above and ensure this is true.
         */
        if (isOpenNow) {
            if (todaysIntervalCount == 1) {
                hoursInfo.detail = getTimeSpanStringForHours(openingHours.get(0));
            } else if (todaysIntervalCount == 2) {
                hoursInfo.detail = mContext.getString(
                        R.string.opening_hours,
                        getTimeSpanStringForHours(openingHours.get(0)),
                        getTimeSpanStringForHours(openingHours.get(1)));
            } else if (afterInterval < openingHours.size()) {
                // This check should not be necessary since if it is currently open, we should not
                // be after the last interval, but just in case, we don't want to crash.
                hoursInfo.detail = mContext.getString(
                        R.string.closes_today_at,
                        getFormattedTimeForCalendar(openingHours.get(afterInterval).second));
            }
        } else { // Currently closed
            final int lastIntervalToday = todaysIntervalCount - 1;
            if (todaysIntervalCount == 0) { // closed today
                hoursInfo.detail = mContext.getString(
                        R.string.opens_tomorrow_at,
                        getFormattedTimeForCalendar(openingHours.get(0).first));
            } else if (currentTime.after(openingHours.get(lastIntervalToday).second)) {
                // Passed hours for today
                if (todaysIntervalCount < openingHours.size()) {
                    // If all of today's intervals are exhausted, assume the next are tomorrow's.
                    hoursInfo.detail = mContext.getString(
                            R.string.opens_tomorrow_at,
                            getFormattedTimeForCalendar(
                                    openingHours.get(todaysIntervalCount).first));
                } else {
                    // Grab the last time it was open today.
                    hoursInfo.detail = mContext.getString(
                            R.string.closed_today_at,
                            getFormattedTimeForCalendar(
                                    openingHours.get(lastIntervalToday).second));
                }
            } else if (afterInterval < openingHours.size()) {
                // This check should not be necessary since if it is currently before the last
                // interval, afterInterval should be less than the count of intervals, but just in
                // case, we don't want to crash.
                hoursInfo.detail = mContext.getString(
                        R.string.opens_today_at,
                        getFormattedTimeForCalendar(openingHours.get(afterInterval).first));
            }
        }

        return hoursInfo;
    }

    String getFormattedTimeForCalendar(Calendar calendar) {
        return DateFormat.getTimeFormat(mContext).format(calendar.getTime());
    }

    String getTimeSpanStringForHours(Pair<Calendar, Calendar> hours) {
        return mContext.getString(R.string.open_time_span,
                getFormattedTimeForCalendar(hours.first),
                getFormattedTimeForCalendar(hours.second));
    }

    /**
     * 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 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;
        }
    }
}