aboutsummaryrefslogtreecommitdiff
path: root/WordPress/src/main/java/org/wordpress/android/ui/stats/models/PostViewsModel.java
blob: 5beb0df95b18f7b5222abe4733a98733a8307828 (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
package org.wordpress.android.ui.stats.models;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wordpress.android.util.AppLog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class PostViewsModel implements Serializable {
    private String mOriginalResponse;

    private int mHighestMonth, mHighestDayAverage, mHighestWeekAverage;
    private String mDate;
    private VisitModel[] mDayViews; //Used to build the graph
    private List<Year> mYears;
    private List<Year> mAverages;
    private List<Week> mWeeks;

    public String getDate() {
        return mDate;
    }

    public String getOriginalResponse() {
        return mOriginalResponse;
    }

    public VisitModel[] getDayViews() {
        return mDayViews;
    }

    public int getHighestMonth() {
        return mHighestMonth;
    }

    public int getHighestDayAverage() {
        return mHighestDayAverage;
    }

    public int getHighestWeekAverage() {
        return mHighestWeekAverage;
    }

    public List<Year> getYears() {
        return mYears;
    }

    public List<Year> getAverages() {
        return mAverages;
    }

    public List<Week> getWeeks() {
        return mWeeks;
    }


    public PostViewsModel(String response) throws JSONException {
            this.mOriginalResponse = response;
            JSONObject responseObj = new JSONObject(response);
            parseResponseObject(responseObj);
    }

    public PostViewsModel(JSONObject response) throws JSONException  {
        if (response == null) {
            return;
        }
        this.mOriginalResponse = response.toString();
        parseResponseObject(response);
    }

    private void parseResponseObject(JSONObject response) throws JSONException  {

        mDate = response.getString("date");
        mHighestDayAverage = response.getInt("highest_day_average");
        mHighestWeekAverage = response.getInt("highest_week_average");
        mHighestMonth = response.getInt("highest_month");
        mYears = new LinkedList<>();
        mAverages = new LinkedList<>();
        mWeeks = new LinkedList<>();

        JSONArray dataJSON =  response.getJSONArray("data");
        if (dataJSON != null) {
            // Read the position/index of each field in the response
            JSONArray fieldsJSON = response.getJSONArray("fields");
            HashMap<String, Integer> fieldColumnsMapping;
            try {
                fieldColumnsMapping = new HashMap<>(2);
                for (int i = 0; i < fieldsJSON.length(); i++) {
                    final String field = fieldsJSON.getString(i);
                    fieldColumnsMapping.put(field, i);
                }
            } catch (JSONException e) {
                AppLog.e(AppLog.T.STATS, "Cannot read the fields indexes from the JSON response", e);
                throw e;
            }

            VisitModel[] visitModels = new VisitModel[dataJSON.length()];
            int viewsColumnIndex = fieldColumnsMapping.get("views");
            int periodColumnIndex = fieldColumnsMapping.get("period");

            for (int i = 0; i < dataJSON.length(); i++) {
                try {
                    JSONArray currentDayData = dataJSON.getJSONArray(i);
                    VisitModel currentVisitModel = new VisitModel();
                    currentVisitModel.setPeriod(currentDayData.getString(periodColumnIndex));
                    currentVisitModel.setViews(currentDayData.getInt(viewsColumnIndex));
                    visitModels[i] = currentVisitModel;
                } catch (JSONException e) {
                    AppLog.e(AppLog.T.STATS, "Cannot create the Visit at index " + i, e);
                }
            }
            mDayViews = visitModels;
        } else {
            mDayViews = null;
        }

        parseYears(response);
        parseAverages(response);
        parseWeeks(response);
    }

    private String[] orderKeys(Iterator keys, int numberOfKeys) {
        // Keys could not be ordered fine. Reordering them.
        String[] orderedKeys = new String[numberOfKeys];
        int i = 0;
        while (keys.hasNext()) {
            orderedKeys[i] = (String)keys.next();
            i++;
        }
        Arrays.sort(orderedKeys);
        return orderedKeys;
    }

    private void parseYears(JSONObject response) {
        // Parse the Years section
        try {
            JSONObject yearsJSON = response.getJSONObject("years");
            // Keys could not be ordered fine. Reordering them.
            String[] orderedKeys = orderKeys(yearsJSON.keys(), yearsJSON.length());

            for (String currentYearKey : orderedKeys) {
                Year currentYear = new Year();
                currentYear.setLabel(currentYearKey);

                JSONObject currentYearObj = yearsJSON.getJSONObject(currentYearKey);
                int total = currentYearObj.getInt("total");
                currentYear.setTotal(total);

                JSONObject monthsJSON = currentYearObj.getJSONObject("months");
                Iterator<String> monthsKeys = monthsJSON.keys();
                List<Month> monthsList = new ArrayList<>(monthsJSON.length());
                while (monthsKeys.hasNext()) {
                    String currentMonthKey = monthsKeys.next();
                    int currentMonthVisits = monthsJSON.getInt(currentMonthKey);
                    monthsList.add(new Month(currentMonthKey, currentMonthVisits));
                }

                Collections.sort(monthsList, new Comparator<Month>() {
                    public int compare(Month o1, Month o2) {
                        int v1 = Integer.parseInt(o1.getMonth());
                        int v2 = Integer.parseInt(o2.getMonth());
                        // ascending order
                        return v1 - v2;
                    }
                });

                currentYear.setMonths(monthsList);
                mYears.add(currentYear);
            }
        } catch (JSONException e) {
            AppLog.e(AppLog.T.STATS, "Cannot parse the Years section", e);
        }
    }

    private void parseAverages(JSONObject response) {
        // Parse the Averages section
        try {
            JSONObject averagesJSON = response.getJSONObject("averages");
            // Keys could not be ordered fine. Reordering them.
            String[] orderedKeys = orderKeys(averagesJSON.keys(), averagesJSON.length());

            for (String currentJSONKey : orderedKeys) {
                Year currentAverage = new Year();
                currentAverage.setLabel(currentJSONKey);

                JSONObject currentAverageJSONObj = averagesJSON.getJSONObject(currentJSONKey);
                currentAverage.setTotal(currentAverageJSONObj.getInt("overall"));

                JSONObject monthsJSON = currentAverageJSONObj.getJSONObject("months");
                Iterator<String> monthsKeys = monthsJSON.keys();
                List<Month> monthsList = new ArrayList<>(monthsJSON.length());
                while (monthsKeys.hasNext()) {
                    String currentMonthKey = monthsKeys.next();
                    int currentMonthVisits = monthsJSON.getInt(currentMonthKey);
                    monthsList.add(new Month(currentMonthKey, currentMonthVisits));
                }
                Collections.sort(monthsList, new java.util.Comparator<Month>() {
                    public int compare(Month o1, Month o2) {
                        int v1 = Integer.parseInt(o1.getMonth());
                        int v2 = Integer.parseInt(o2.getMonth());
                        // ascending order
                        return v1 - v2;
                    }
                });

                currentAverage.setMonths(monthsList);
                mAverages.add(currentAverage);
            }
        } catch (JSONException e) {
            AppLog.e(AppLog.T.STATS, "Cannot parse the Averages section", e);
        }
    }

    private void parseWeeks(JSONObject response) {
        // Parse the Weeks section
        try {
            JSONArray weeksJSON = response.getJSONArray("weeks");
            for (int i = 0; i < weeksJSON.length(); i++) {
                Week currentWeek = new Week();
                JSONObject currentWeekJSON = weeksJSON.getJSONObject(i);

                currentWeek.setTotal(currentWeekJSON.getInt("total"));
                currentWeek.setAverage(currentWeekJSON.getInt("average"));
                try {
                    if (i == 0 ) {
                        currentWeek.setChange(0);
                    } else {
                        currentWeek.setChange(currentWeekJSON.getInt("change"));
                    }
                } catch (JSONException e){
                    AppLog.w(AppLog.T.STATS, "Cannot parse the change value in weeks section. Trying to understand the meaning: 42!!");
                    //  if i == 0 is the first week. if not it could mean infinity
                    String aProblematicValue = currentWeekJSON.get("change").toString();
                    if (aProblematicValue.contains("infinity")) {
                        currentWeek.setChange(Integer.MAX_VALUE);
                    } else {
                        currentWeek.setChange(0);
                    }
                }

                JSONArray daysJSON = currentWeekJSON.getJSONArray("days");
                for (int j = 0; j < daysJSON.length(); j++) {
                    Day currentDay = new Day();
                    JSONObject dayJSON = daysJSON.getJSONObject(j);
                    currentDay.setCount(dayJSON.getInt("count"));
                    currentDay.setDay(dayJSON.getString("day"));
                    currentWeek.getDays().add(currentDay);
                }
                mWeeks.add(currentWeek);
            }
        } catch (JSONException e) {
            AppLog.e(AppLog.T.STATS, "Cannot parse the Weeks section", e);
        }
    }

    public class Day implements Serializable {
        private int mCount;
        private String mDay;

        public String getDay() {
            return mDay;
        }

        public void setDay(String day) {
            this.mDay = day;
        }

        public int getCount() {
            return mCount;
        }

        public void setCount(int count) {
            this.mCount = count;
        }
    }

    public class Week implements Serializable {
        int mChange;
        int mTotal;
        int mAverage;
        List<Day> mDays = new LinkedList<>();

        public int getTotal() {
            return mTotal;
        }

        public void setTotal(int total) {
            this.mTotal = total;
        }

        public int getAverage() {
            return mAverage;
        }

        public void setAverage(int average) {
            this.mAverage = average;
        }

        public int getChange() {
            return mChange;
        }

        public void setChange(int change) {
            this.mChange = change;
        }

        public List<Day> getDays() {
            return mDays;
        }

        public void setDays(List<Day> days) {
            this.mDays = days;
        }
    }

    public class Year implements Serializable {
        private String mLabel;
        private int mTotal;
        private List<Month> mMonths;

        public List<Month> getMonths() {
            return mMonths;
        }

        public void setMonths(List<Month> months) {
            mMonths = months;
        }

        public String getLabel() {
            return mLabel;
        }

        public void setLabel(String label) {
            this.mLabel = label;
        }

        public int getTotal() {
            return mTotal;
        }

        public void setTotal(int total) {
            this.mTotal = total;
        }
    }

    public class Month implements Serializable {
        private final int mCount;
        private final String mMonth;

        Month(String label, int count) {
            this.mMonth = label;
            this.mCount = count;
        }

        public String getMonth() {
            return mMonth;
        }
        public int getCount() {
            return mCount;
        }
    }
}