Project

General

Profile

Download (13.6 KB) Statistics
| Branch: | Tag: | Revision:

magiccube / src / main / java / org / distorted / external / RubikScores.java @ 84d746d7

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is free software: you can redistribute it and/or modify                            //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Magic Cube is distributed in the hope that it will be useful,                                 //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Magic Cube.  If not, see <http://www.gnu.org/licenses/>.                           //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.external;
21

    
22
import java.util.HashMap;
23
import java.util.UUID;
24

    
25
import android.content.Context;
26
import android.content.SharedPreferences;
27
import android.telephony.TelephonyManager;
28

    
29
import com.google.firebase.crashlytics.FirebaseCrashlytics;
30

    
31
import org.distorted.main.BuildConfig;
32
import org.distorted.objects.RubikObject;
33
import org.distorted.objects.RubikObjectList;
34

    
35
import static org.distorted.objects.RubikObjectList.MAX_LEVEL;
36

    
37
///////////////////////////////////////////////////////////////////////////////////////////////////
38
// hold my own scores, and some other statistics.
39

    
40
public class RubikScores
41
  {
42
  public static final int MULT = 1000000;
43
  public static final long NO_RECORD = Long.MAX_VALUE;
44
  private static RubikScores mThis;
45

    
46
  private String mName, mCountry;
47
  private boolean mNameIsVerified;
48
  private int mNumRuns;
49
  private int mNumPlays;
50
  private int mNumWins;
51
  private int mDeviceID;
52

    
53
  private static class MapValue
54
    {
55
    long record;
56
    boolean submitted;
57

    
58
    MapValue(long rec,int sub)
59
      {
60
      record    = rec;
61
      submitted = sub!=0;
62
      }
63
    }
64

    
65
  private final HashMap<Integer,MapValue> mMap;
66

    
67
///////////////////////////////////////////////////////////////////////////////////////////////////
68

    
69
  private RubikScores()
70
    {
71
    mMap = new HashMap<>();
72

    
73
    mName = "";
74
    mCountry = "un";
75

    
76
    mNameIsVerified = false;
77

    
78
    mNumPlays= -1;
79
    mNumRuns = -1;
80
    mDeviceID= -1;
81
    mNumWins =  0;
82
    }
83

    
84
///////////////////////////////////////////////////////////////////////////////////////////////////
85

    
86
  private int mapKey(int object,int level)
87
    {
88
    return object*MULT + level;
89
    }
90

    
91
///////////////////////////////////////////////////////////////////////////////////////////////////
92

    
93
  private int privateGetDeviceID()
94
    {
95
    int id;
96

    
97
    try
98
      {
99
      String s = UUID.randomUUID().toString();
100
      id = s.hashCode();
101
      }
102
    catch(Exception ex)
103
      {
104
      id = 0;
105
      android.util.Log.e("scores", "Exception in getDeviceID()");
106
      }
107

    
108
    return id<0 ? -id : id;
109
    }
110

    
111
///////////////////////////////////////////////////////////////////////////////////////////////////
112

    
113
  synchronized void successfulSubmit()
114
    {
115
    mNameIsVerified = true;
116

    
117
    for(int key: mMap.keySet())
118
      {
119
      MapValue value = mMap.get(key);
120
      if( value!=null ) value.submitted = true;
121
      }
122
    }
123

    
124
///////////////////////////////////////////////////////////////////////////////////////////////////
125

    
126
  int getDeviceID()
127
    {
128
    return mDeviceID;
129
    }
130

    
131
///////////////////////////////////////////////////////////////////////////////////////////////////
132

    
133
  synchronized boolean thereAreUnsubmittedRecords()
134
    {
135
    for(int key: mMap.keySet())
136
      {
137
      MapValue value = mMap.get(key);
138
      if( value!=null && !value.submitted && value.record<NO_RECORD) return true;
139
      }
140

    
141
    return false;
142
    }
143

    
144
///////////////////////////////////////////////////////////////////////////////////////////////////
145

    
146
  synchronized String getRecordList(String strObj, String strLvl, String strTim)
147
    {
148
    StringBuilder builderObj = new StringBuilder();
149
    StringBuilder builderLvl = new StringBuilder();
150
    StringBuilder builderTim = new StringBuilder();
151
    boolean first = true;
152

    
153
    for(int key: mMap.keySet())
154
      {
155
      MapValue value = mMap.get(key);
156

    
157
      if( value!=null && !value.submitted && value.record<NO_RECORD)
158
        {
159
        if( !first )
160
          {
161
          builderObj.append(',');
162
          builderLvl.append(',');
163
          builderTim.append(',');
164
          }
165
        first=false;
166

    
167
        RubikObject object = RubikObjectList.getObject(key/MULT);
168

    
169
        if( object!=null )
170
          {
171
          builderObj.append(object.getUpperName());
172
          builderLvl.append(key%MULT);
173
          builderTim.append(value.record);
174
          }
175
        }
176
      }
177

    
178
    return strObj+builderObj.toString()+strLvl+builderLvl.toString()+strTim+builderTim.toString();
179
    }
180

    
181
///////////////////////////////////////////////////////////////////////////////////////////////////
182
// Public API
183
///////////////////////////////////////////////////////////////////////////////////////////////////
184

    
185
  public boolean isVerified()
186
    {
187
    return mNameIsVerified;
188
    }
189

    
190
///////////////////////////////////////////////////////////////////////////////////////////////////
191

    
192
  public int getNumPlays()
193
    {
194
    return mNumPlays;
195
    }
196

    
197
///////////////////////////////////////////////////////////////////////////////////////////////////
198

    
199
  public int getNumRuns()
200
    {
201
    return mNumRuns;
202
    }
203

    
204
///////////////////////////////////////////////////////////////////////////////////////////////////
205

    
206
  public String getName()
207
    {
208
    return mName;
209
    }
210

    
211
///////////////////////////////////////////////////////////////////////////////////////////////////
212

    
213
  public String getCountry()
214
    {
215
    return mCountry;
216
    }
217

    
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219

    
220
  public void incrementNumPlays()
221
    {
222
    mNumPlays++;
223
    }
224

    
225
///////////////////////////////////////////////////////////////////////////////////////////////////
226

    
227
  public void incrementNumRuns()
228
    {
229
    mNumRuns++;
230
    }
231

    
232
///////////////////////////////////////////////////////////////////////////////////////////////////
233

    
234
  public int incrementNumWins()
235
    {
236
    mNumWins++;
237
    return mNumWins;
238
    }
239

    
240
///////////////////////////////////////////////////////////////////////////////////////////////////
241

    
242
  public void setName(String newName)
243
    {
244
    mName = newName;
245
    }
246

    
247
///////////////////////////////////////////////////////////////////////////////////////////////////
248

    
249
  public synchronized boolean setRecord(int object, int level, long record)
250
    {
251
    int key = mapKey(object,level)-1; // -1 - historical reasons; previous versions saved it like this.
252
    MapValue oldValue = mMap.get(key);
253

    
254
    if( oldValue==null )
255
      {
256
      MapValue value = new MapValue(record,0);
257
      mMap.put(key,value);
258
      return true;
259
      }
260

    
261
    long oldRecord = oldValue.record;
262

    
263
    if( oldRecord>record)
264
      {
265
      MapValue value = new MapValue(record,0);
266
      mMap.put(key,value);
267
      return true;
268
      }
269

    
270
    return false;
271
    }
272
///////////////////////////////////////////////////////////////////////////////////////////////////
273

    
274
  public synchronized long getRecord(int object, int level)
275
    {
276
    int key = mapKey(object,level);
277
    MapValue value = mMap.get(key);
278
    return value!=null ? value.record : NO_RECORD;
279
    }
280

    
281
///////////////////////////////////////////////////////////////////////////////////////////////////
282

    
283
  public synchronized boolean isSolved(int object, int level)
284
    {
285
    int key = mapKey(object,level);
286
    MapValue value = mMap.get(key);
287
    return value!=null && value.record<NO_RECORD;
288
    }
289

    
290
///////////////////////////////////////////////////////////////////////////////////////////////////
291

    
292
  public void setCountry(Context context)
293
    {
294
    TelephonyManager tM =((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
295

    
296
    if( tM!=null )
297
      {
298
      mCountry = tM.getSimCountryIso();
299

    
300
      if( mCountry==null || mCountry.length()<=1 )
301
        {
302
        mCountry = tM.getNetworkCountryIso();
303
        }
304
      }
305

    
306
    // Special case: Dominicana. Its ISO-3166-alpha-2 country code is 'do' which we can't have here
307
    // because we later on map this to a resource name (the flag) and 'do' is a reserved Java keyword
308
    // and can't be a resource name.
309

    
310
    if( mCountry.equals("do") ) mCountry = "dm";
311
    }
312

    
313
///////////////////////////////////////////////////////////////////////////////////////////////////
314

    
315
  public void setCountry(String country)
316
    {
317
    mCountry = country;
318

    
319
    if( mCountry.equals("do") ) mCountry = "dm";  // see above
320
    }
321

    
322
///////////////////////////////////////////////////////////////////////////////////////////////////
323

    
324
  public static RubikScores getInstance()
325
    {
326
    if( mThis==null ) mThis = new RubikScores();
327
    return mThis;
328
    }
329

    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331

    
332
  public synchronized void savePreferences(SharedPreferences.Editor editor)
333
    {
334
    int numObjects = RubikObjectList.getNumObjects();
335
    StringBuilder builder = new StringBuilder();
336

    
337
    for(int level=0; level<MAX_LEVEL; level++)
338
      {
339
      builder.setLength(0);
340

    
341
      for(int object=0; object<numObjects; object++)
342
        {
343
        int key = mapKey(object,level);
344
        RubikObject obj = RubikObjectList.getObject(object);
345
        MapValue value = mMap.get(key);
346

    
347
        if( obj!=null && value!=null && value.record<NO_RECORD )
348
          {
349
          builder.append(obj.getUpperName());
350
          builder.append("=");
351
          builder.append(value.record);
352
          builder.append(",");
353
          builder.append(value.submitted ? 1:0 );
354
          builder.append(" ");
355
          }
356
        }
357

    
358
      editor.putString("scores_record"+level, builder.toString());
359
      }
360

    
361
    editor.putString("scores_name"  , mName  );
362
    editor.putBoolean("scores_isVerified", mNameIsVerified);
363
    editor.putInt("scores_numPlays", mNumPlays);
364
    editor.putInt("scores_numRuns" , mNumRuns );
365
    editor.putInt("scores_deviceid", mDeviceID);
366
    editor.putInt("scores_review"  , mNumWins );
367
    }
368

    
369
///////////////////////////////////////////////////////////////////////////////////////////////////
370

    
371
  public synchronized void restorePreferences(SharedPreferences preferences)
372
    {
373
    String recordStr, subStr, nameStr, timeStr, submStr, errorStr="";
374
    int start, end, equals, comma, object, subm;
375
    long time;
376
    boolean thereWasError = false;
377
    int numObjects = RubikObjectList.getNumObjects();
378

    
379
    for(int level=0; level<MAX_LEVEL; level++)
380
      {
381
      start = end = 0;
382
      recordStr = preferences.getString("scores_record"+level, "");
383

    
384
      while( end!=-1 )
385
        {
386
        end = recordStr.indexOf(" ", start);
387

    
388
        if( end==-1 ) subStr = recordStr.substring(start);
389
        else          subStr = recordStr.substring(start,end);
390

    
391
        start = end+1;
392

    
393
        equals = subStr.indexOf("=");
394
        comma  = subStr.indexOf(",");
395

    
396
        if( equals>=0 && comma>=0 )
397
          {
398
          nameStr = subStr.substring(0,equals);
399
          timeStr = subStr.substring(equals+1,comma);
400
          submStr = subStr.substring(comma+1);
401

    
402
          object = RubikObjectList.getOrdinal(nameStr);
403

    
404
          if( object>=0 && object<numObjects )
405
            {
406
            time = Long.parseLong(timeStr);
407
            subm = Integer.parseInt(submStr);
408

    
409
            if( subm>=0 && subm<=1 )
410
              {
411
              MapValue value = new MapValue(time,subm);
412
              int key = mapKey(object,level);
413
              mMap.put(key,value);
414
              }
415
            else
416
              {
417
              errorStr += ("error1: subm="+subm+" obj: "+nameStr+"\n");
418
              thereWasError= true;
419
              }
420
            }
421
          else
422
            {
423
            errorStr += ("error2: object="+object+" obj: "+nameStr+"\n");
424
            thereWasError = true;
425
            }
426
          }
427
        }
428
      }
429

    
430
    mName           = preferences.getString("scores_name"  , "" );
431
    mNameIsVerified = preferences.getBoolean("scores_isVerified", false);
432
    mNumPlays       = preferences.getInt("scores_numPlays", 0);
433
    mNumRuns        = preferences.getInt("scores_numRuns" , 0);
434
    mDeviceID       = preferences.getInt("scores_deviceid",-1);
435
    mNumWins        = preferences.getInt("scores_review"  , 0);
436

    
437
    if( mDeviceID==-1 ) mDeviceID = privateGetDeviceID();
438

    
439
    if( thereWasError ) recordDBError(errorStr);
440
    }
441

    
442
///////////////////////////////////////////////////////////////////////////////////////////////////
443

    
444
  public void recordDBError(String message)
445
    {
446
    if( BuildConfig.DEBUG )
447
      {
448
      android.util.Log.e("scores", message);
449
      }
450
    else
451
      {
452
      Exception ex = new Exception(message);
453
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
454
      crashlytics.setCustomKey("scores" , message);
455
      crashlytics.recordException(ex);
456
      }
457
    }
458
  }
(3-3/4)