Proyectos de Subversion Android Microlearning

Rev

Rev 22 | Rev 25 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
package com.cesams.twogetskills.activity;
2
 
3
import androidx.activity.result.ActivityResultLauncher;
4
import androidx.activity.result.contract.ActivityResultContracts;
5
import androidx.annotation.NonNull;
6
import androidx.appcompat.app.ActionBarDrawerToggle;
7
import androidx.appcompat.app.AlertDialog;
8
import androidx.appcompat.app.AppCompatActivity;
9
import androidx.core.app.NotificationCompat;
10
import androidx.core.view.GravityCompat;
11
import androidx.fragment.app.Fragment;
12
import androidx.fragment.app.FragmentTransaction;
13
 
14
import android.accounts.Account;
15
import android.accounts.AccountManager;
16
import android.app.NotificationChannel;
17
import android.app.NotificationManager;
18
import android.app.PendingIntent;
19
import android.content.ContentResolver;
20
import android.content.DialogInterface;
21
import android.net.ConnectivityManager;
22
import android.os.Build;
23
import android.text.TextUtils;
24
import android.util.Log;
25
import android.content.Context;
26
import android.content.Intent;
27
import android.content.IntentFilter;
28
import android.os.Bundle;
29
import android.view.Menu;
30
import android.view.MenuItem;
31
import android.view.View;
32
import android.widget.ImageView;
33
import android.widget.ProgressBar;
34
import android.widget.TextView;
35
 
36
 
37
import com.bumptech.glide.Glide;
38
import com.bumptech.glide.load.engine.DiskCacheStrategy;
39
import com.bumptech.glide.load.model.GlideUrl;
40
import com.bumptech.glide.load.model.LazyHeaders;
41
import com.bumptech.glide.request.RequestOptions;
42
import com.cesams.twogetskills.Configuration;
43
import com.cesams.twogetskills.dao.AnswerDao;
44
import com.cesams.twogetskills.dao.AppDatabase;
45
import com.cesams.twogetskills.dao.CapsuleDao;
46
import com.cesams.twogetskills.dao.CompanyDao;
47
import com.cesams.twogetskills.dao.DatabaseHelper;
48
import com.cesams.twogetskills.dao.ProgressDao;
49
import com.cesams.twogetskills.dao.QuestionDao;
50
import com.cesams.twogetskills.dao.QuizDao;
51
import com.cesams.twogetskills.dao.SlideDao;
52
import com.cesams.twogetskills.dao.SyncDao;
53
import com.cesams.twogetskills.dao.TopicDao;
54
import com.cesams.twogetskills.dao.UserExtendedDao;
55
import com.cesams.twogetskills.dao.UserLogDao;
56
import com.cesams.twogetskills.entity.UserExtended;
57
import com.cesams.twogetskills.fragment.CapsuleFragment;
58
import com.cesams.twogetskills.fragment.CompanyFragment;
59
import com.cesams.twogetskills.fragment.FinishCapsuleFragment;
60
import com.cesams.twogetskills.fragment.FinishTopicFragment;
61
import com.cesams.twogetskills.fragment.GalleryFragment;
62
import com.cesams.twogetskills.fragment.ProgressFragment;
63
import com.cesams.twogetskills.fragment.SlideFragment;
64
import com.cesams.twogetskills.fragment.TimelineFragment;
65
import com.cesams.twogetskills.fragment.TopicFragment;
66
import com.cesams.twogetskills.fragment.UserProfileFragment;
67
import com.cesams.twogetskills.library.Http;
68
import com.cesams.twogetskills.library.MD5;
69
import com.cesams.twogetskills.library.UniqueID;
70
import com.cesams.twogetskills.entity.Answer;
71
import com.cesams.twogetskills.entity.Capsule;
72
import com.cesams.twogetskills.entity.Company;
73
import com.cesams.twogetskills.entity.Progress;
74
import com.cesams.twogetskills.entity.Question;
75
import com.cesams.twogetskills.entity.Quiz;
76
import com.cesams.twogetskills.entity.Slide;
77
import com.cesams.twogetskills.entity.Sync;
78
import com.cesams.twogetskills.entity.Topic;
79
import com.cesams.twogetskills.entity.UserLog;
80
import com.cesams.twogetskills.preference.Preference;
81
import com.cesams.twogetskills.receiver.ConnectivityReceiver;
82
import com.cesams.twogetskills.receiver.InternalReceiver;
83
import com.cesams.twogetskills.room.ResultCount;
84
import com.google.android.material.snackbar.Snackbar;
85
import com.google.android.material.navigation.NavigationView;
86
 
87
import androidx.drawerlayout.widget.DrawerLayout;
88
import androidx.appcompat.widget.Toolbar;
8 gabriel 89
import androidx.room.Database;
90
 
1 efrain 91
import com.cesams.twogetskills.Constants;
92
import com.cesams.twogetskills.R;
93
 
94
import com.cesams.twogetskills.fragment.IntroFragment;
95
import com.cesams.twogetskills.fragment.SigninFragment;
96
import com.cesams.twogetskills.skeleton.ITwoGetSkills;
97
 
98
import org.json.JSONArray;
99
import org.json.JSONException;
100
import org.json.JSONObject;
101
 
102
import java.io.IOException;
103
import java.text.SimpleDateFormat;
104
import java.util.Calendar;
105
import java.util.Date;
106
import java.util.HashMap;
107
import java.util.List;
108
import java.util.Random;
109
import java.util.TimeZone;
110
 
111
//import de.hdodenhof.circleimageview.CircleImageView;
112
import okhttp3.Call;
113
import okhttp3.FormBody;
114
import okhttp3.OkHttpClient;
115
import okhttp3.Request;
116
import okhttp3.RequestBody;
117
import okhttp3.Response;
118
 
119
public class MainActivity extends  AppCompatActivity implements ITwoGetSkills,NavigationView.OnNavigationItemSelectedListener {
120
    private boolean isSyncDevice = false;
121
    private boolean isSyncToken = false;
122
    private boolean isSyncBatch = false;
123
    private boolean isForeground = false;
6 gabriel 124
    private boolean issmartlockloginrun = false;
1 efrain 125
 
126
    private final static String PREFIX_FRAG = "FRAG";
127
    private final static String TAG = "C2GS - MainActivity";
128
 
129
    private DrawerLayout mDrawer;
130
    private ActionBarDrawerToggle mDrawerToggle;
131
 
132
    private HashMap<String, Fragment> fragmentHashMap;
133
 
134
    private ImageView navHeaderUserImage;
135
 
136
    private TextView navHeaderUserName;
137
    private TextView navHeaderUserEmail;
138
    private TextView textViewMessageNotConnection;
139
 
140
 
141
 
142
    private Preference preference;
143
    private boolean connected = false;
144
    private ConnectivityReceiver mConnectivityReceiver;
145
    private InternalReceiver mInternalReceiver;
146
    private ProgressBar mProgressBar;
147
 
148
    private Account mAccount;
149
    private AppDatabase mAppDatabase;
150
 
151
 
152
 
153
    ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(
154
            new ActivityResultContracts.StartActivityForResult(),
155
            result -> {
156
                if(result.getResultCode() == RESULT_OK) {
6 gabriel 157
                    boolean completed = result.getData().hasExtra("completed") && result.getData().getBooleanExtra("completed", false);
1 efrain 158
                    int requestCode = result.getData().hasExtra("requestCode") ? result.getData().getIntExtra("requestCode", 0) : 0;
159
                    if(requestCode == Constants.REQUEST_CODE_QUIZ) {
160
                        createProgressAndSyncRecord(preference.getSlideUuidActive(), completed, true, false);
161
                    } else  if(requestCode == Constants.REQUEST_CODE_AUDIO_VIDEO) {
162
                        createProgressAndSyncRecord(preference.getSlideUuidActive(), completed, false, true);
163
                    } else {
164
                        createProgressAndSyncRecord(preference.getSlideUuidActive(), completed, false, false);
165
                    }
166
                }
167
            }
168
    );
169
 
170
 
171
    @Override
172
    protected void onCreate(Bundle savedInstanceState) {
173
        super.onCreate(savedInstanceState);
174
        setContentView(R.layout.activity_main);
175
 
176
        Log.d(TAG, "MainActivity onCreate");
177
 
178
        /**** CANAL DE NOTIFICACIONES **/
179
        createNotificationChannel();
180
 
181
        /*** CUENTAS DE SINCRONIZACION **/
182
        mAccount =  CreateSyncAccount(this);
183
 
184
 
185
        // Get the content resolver for your app
186
        //mResolver = getContentResolver();
187
 
188
        mAppDatabase = DatabaseHelper.getInstance(this).getAppDatabase();
189
 
190
        preference = new Preference(this);
191
 
192
        if(TextUtils.isEmpty(preference.getDeviceUuid())) {
193
            String uuid = UniqueID.id(this);
194
            preference.setDeviceUuid(uuid);
195
            preference.save(this);
196
 
197
            Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_DEVICE, uuid);
198
            mAppDatabase.getSyncDao().insert(sync);
199
 
200
            if(!TextUtils.isEmpty(preference.getDeviceToken())) {
201
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, preference.getDeviceToken());
202
                mAppDatabase.getSyncDao().insert(sync);
203
            }
204
        }
205
 
206
        fragmentHashMap = new HashMap<>();
207
 
208
        mProgressBar = findViewById(R.id.progressBar);
6 gabriel 209
        Toolbar mToolbar = findViewById(R.id.toolbar);
1 efrain 210
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
211
 
212
        mDrawer = findViewById(R.id.drawer_layout);
213
        mDrawerToggle = new ActionBarDrawerToggle(
214
                this, mDrawer, mToolbar, R.string.navigation_drawer_open,
215
                R.string.navigation_drawer_close);
216
 
217
        mDrawerToggle.setToolbarNavigationClickListener(v -> onBackPressed());
218
 
219
        mDrawer.addDrawerListener(mDrawerToggle);
220
        mDrawerToggle.syncState();
221
 
222
        NavigationView navigationView = findViewById(R.id.navigation_view);
223
        navigationView.setNavigationItemSelectedListener(this);
224
 
225
        View header = navigationView.getHeaderView(0);
226
        //navHeaderUserImage = (CircleImageView) header.findViewById(R.id.nav_header_user_image);
4 gabriel 227
        navHeaderUserImage = header.findViewById(R.id.nav_header_user_image);
228
        navHeaderUserName = header.findViewById(R.id.nav_header_user_name);
229
        navHeaderUserEmail =  header.findViewById(R.id.nav_header_user_email);
1 efrain 230
 
4 gabriel 231
        textViewMessageNotConnection = findViewById(R.id.main_activity_text_view_message_not_connection);
1 efrain 232
 
233
        mConnectivityReceiver = new ConnectivityReceiver();
234
        registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
235
 
236
        IntentFilter intentFilterInternal = new IntentFilter();
237
        intentFilterInternal.addAction(Constants.BROADCAST_TYPE_NOTIFICATION);
238
        intentFilterInternal.addAction(Constants.BROADCAST_TYPE_TOKEN);
239
        intentFilterInternal.addAction(Constants.BROADCAST_TYPE_COMMAND);
240
        intentFilterInternal.addAction(Constants.BROADCAST_TYPE_SYNC_TO_SERVER_OR_CHECK_CHANGES);
241
 
242
        mInternalReceiver = new InternalReceiver();
243
        registerReceiver(mInternalReceiver, intentFilterInternal);
244
 
245
    }
246
 
247
    @Override
248
    protected void onDestroy() {
249
        super.onDestroy();
250
 
251
        try  {
252
            unregisterReceiver(mConnectivityReceiver);
253
            unregisterReceiver(mInternalReceiver);
254
        } catch (IllegalArgumentException e) {
255
            e.printStackTrace();
256
        }
257
    }
258
 
259
 
260
    @Override
261
    protected void onResume() {
262
        super.onResume();
263
        isForeground = true;
264
 
265
        if(preference == null) {
266
            preference = new Preference(this);
22 efrain 267
        } else {
268
            preference.load(this);
1 efrain 269
        }
270
        reloadNavHeader();
271
 
6 gabriel 272
        Log.e("Se ejecuta", "On resumen");
273
 
1 efrain 274
        if(TextUtils.isEmpty(preference.getUserUuid())) {
6 gabriel 275
 
276
            //Verifico que el teclado no vaya a relanzar el fragment de intro al usar Google Smartlock para traer
277
            //Informacion de inicio de sesion almacenada en su cuenta personal de Google
278
            if (!issmartlockloginrun) {
279
                invokeFragment(Constants.IDX_FRAGMENT_INTRO);
280
                issmartlockloginrun= true;
281
            }
282
 
283
 
1 efrain 284
        } else {
285
            if(preference.getFragmentIdxActive() == 0) {
286
                invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
287
            } else {
288
                invokeFragment(preference.getFragmentIdxActive());
289
            }
290
        }
291
 
292
    }
293
 
294
    @Override
295
    protected void onPause() {
296
        super.onPause();
297
 
298
        isForeground = false;
299
        preference.save(this);
300
    }
301
 
302
    @Override
24 gabriel 303
    protected void onRestart() {
304
        super.onRestart();
305
 
306
        if(preference == null) {
307
            preference = new Preference(this);
308
        } else {
309
            preference.load(this);
310
        }
311
 
312
 
313
    }
314
 
315
    @Override
316
    protected void onStop() {
317
        super.onStop();
318
        preference.save(this);
319
 
320
    }
321
 
322
    @Override
1 efrain 323
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
324
        int title;
325
        mDrawer.closeDrawers();
326
 
327
        switch (menuItem.getItemId()) {
328
            case R.id.nav_topics :
329
                setTitleActionBar(getString(R.string.menu_topics));
330
                invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
331
                break;
332
            case R.id.nav_timeline:
333
                setTitleActionBar(getString(R.string.menu_timeline));
334
                invokeFragment(Constants.IDX_FRAGMENT_TIMELINE);
335
 
336
                break;
337
            case R.id.nav_progress:
338
 
339
                if(preference.getCompanyCount() > 1) {
340
                    invokeFragment(Constants.IDX_FRAGMENT_COMPANIES);
341
                }  else {
342
                    setTitleActionBar(getString(R.string.menu_progress));
343
                    invokeFragment(Constants.IDX_FRAGMENT_PROGRESS);
344
                }
345
                break;
346
 
347
            case R.id.nav_userprofile:
348
                setTitleActionBar(getString(R.string.menu_user_profile));
349
                invokeFragment(Constants.IDX_FRAGMENT_USER_PROFILE);
350
                break;
351
 
352
            case R.id.nav_exit_app:
353
                setTitleActionBar(getString(R.string.menu_exit));
354
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
355
                builder.setTitle(R.string.alter_dialog_close_app_title);
356
                builder.setMessage(R.string.alter_dialog_close_app_message);
357
                builder.setNegativeButton(R.string.alter_dialog_button_no, new DialogInterface.OnClickListener() {
358
                    @Override
359
                    public void onClick(DialogInterface dialog, int which) {
360
 
361
                    }
362
                });
363
                builder.setPositiveButton(R.string.alter_dialog_button_yes, new DialogInterface.OnClickListener() {
364
                    @Override
365
                    public void onClick(DialogInterface dialog, int which) {
366
                        signout();
367
                    }
368
                });
369
 
370
                AlertDialog dialog = builder.create();
371
                dialog.show();
372
 
373
                break;
374
 
375
            default:
376
                throw new IllegalArgumentException("menu option not implemented!!");
377
        }
378
 
379
        mDrawer.closeDrawer(GravityCompat.START);
380
 
381
        return true;
382
    }
383
 
384
    private void createNotificationChannel() {
385
        // Create the NotificationChannel, but only on API 26+ because
386
        // the NotificationChannel class is new and not in the support library
4 gabriel 387
        CharSequence name = getString(R.string.channel_name);
388
        String description = getString(R.string.channel_description);
389
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
390
        NotificationChannel channel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, name, importance);
391
        channel.setDescription(description);
392
        channel.setShowBadge(true);
1 efrain 393
 
394
 
4 gabriel 395
        // Register the channel with the system; you can't change the importance
396
        // or other notification behaviors after this
397
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
398
        notificationManager.createNotificationChannel(channel);
1 efrain 399
    }
400
 
401
 
402
    @Override
403
    public void showFcmNotification(String title, String body, int new_capsules)
404
    {
405
 
406
        NotificationCompat.Builder builder =
407
                new NotificationCompat.Builder(MainActivity.this, Constants.NOTIFICATION_CHANNEL_ID)
408
                        .setSmallIcon(R.drawable.ic_notificacion) //set icon for notification
409
                        .setContentTitle(title) //set title of notification
410
                        .setContentText(body)//this is notification message
411
                        .setAutoCancel(true) // makes auto cancel of notification
412
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of notification
413
 
414
        if(new_capsules > 0) {
415
            builder.setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE);
416
            builder.setNumber(new_capsules);
417
        }
418
 
419
        Intent notificationIntent = new Intent(this, MainActivity.class);
420
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
421
        //notification message will get at NotificationView
422
        notificationIntent.putExtra(title, body);
423
 
424
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
15 gabriel 425
                PendingIntent.FLAG_IMMUTABLE);
1 efrain 426
        builder.setContentIntent(pendingIntent);
427
 
428
        // Add as notification
429
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
430
        manager.notify(0, builder.build());
431
 
432
 
433
        if(new_capsules > 0) {
434
 
435
            String message = new_capsules == 1
436
                    ? "Hay 1 cápsula nueva disponible"
437
                    : "Hay " + new_capsules + " cápsulas disponible";
438
 
439
            showMessageSnackBarWithClose(message);
440
        } else {
441
            showMessageSnackBarWithClose(body);
442
        }
443
 
444
 
445
    }
446
 
447
    @Override
448
    public void signout()
449
    {
450
        mAppDatabase.getAnswerDao().removeAll();
451
        mAppDatabase.getQuestionDao().removeAll();
452
        mAppDatabase.getQuizDao().removeAll();
453
        mAppDatabase.getSlideDao().removeAll();
454
        mAppDatabase.getCapsuleDao().removeAll();
455
        mAppDatabase.getTopicDao().removeAll();
456
        mAppDatabase.getUserExtendedDao().removeAll();
457
 
458
 
459
        preference.setUserUuid("");
460
        preference.setFirstName("");
461
        preference.setLastName("");
462
        preference.setEmail("");
463
        preference.setImage("");
464
        preference.setMaxDateChanges("");
465
        preference.setCompanyCount(0);
466
        preference.setCompanyUuidActive("");
467
        preference.setTopicUuidActive("");
468
        preference.setCapsuleUuidActive("");
469
        preference.setSlideUuidActive("");
470
        preference.save(this);
471
 
472
        invokeFragment(Constants.IDX_FRAGMENT_INTRO);
473
    }
474
 
475
    @Override
476
    public void onBackPressed() {
477
 
478
        //super.onBackPressed();
479
        switch (preference.getFragmentIdxActive())
480
        {
481
 
482
/*
483
            case Constants.IDX_FRAGMENT_INTRO :
484
            case Constants.IDX_FRAGMENT_SIGNIN  :
485
            case Constants.IDX_FRAGMENT_TOPICS  :
486
                finish();
487
                return;*/
488
 
489
            case Constants.IDX_FRAGMENT_PROGRESS :
490
               if(preference.getCompanyCount() > 1) {
491
                   invokeFragment(Constants.IDX_FRAGMENT_COMPANIES);
492
               } else {
493
                   invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
494
               }
495
               break;
496
 
497
            case Constants.IDX_FRAGMENT_COMPANIES:
498
            case Constants.IDX_FRAGMENT_TIMELINE  :
499
            case Constants.IDX_FRAGMENT_CAPSULES :
500
            case Constants.IDX_FRAGMENT_FINISH_TOPIC :
501
 
502
                preference.setTopicUuidActive("");
503
                preference.setCapsuleUuidActive("");
504
                preference.setSlideUuidActive("");
505
                preference.save(this);
506
 
507
                invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
508
                return;
509
 
510
            case Constants.IDX_FRAGMENT_SLIDES :
511
                invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
512
                return;
513
 
514
            case Constants.IDX_FRAGMENT_GALLERY :
515
                invokeFragment(Constants.IDX_FRAGMENT_SLIDES);
516
                return;
517
 
518
            case Constants.IDX_FRAGMENT_FINISH_CAPSULE :
519
                preference.setCapsuleUuidActive("");
520
                preference.setSlideUuidActive("");
521
                preference.save(this);
522
 
523
                invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
524
                return;
525
 
526
        }
527
    }
528
 
529
 
530
 
531
    @Override
532
    public void hideProgressBar() {
533
 
534
        //accessing it from ui-thread
535
        runOnUiThread(new Runnable() {
536
            @Override
537
            public void run() {
538
                mProgressBar.setVisibility(View.INVISIBLE);
539
            }
540
        });
541
 
542
    }
543
 
544
    @Override
545
    public void showProgressBar() {
546
        runOnUiThread(new Runnable() {
547
            @Override
548
            public void run() {
549
                mProgressBar.setVisibility(View.VISIBLE);
550
            }
551
        });
552
 
553
 
554
    }
555
 
556
 
557
 
558
 
559
 
560
    @Override
561
    public boolean onCreateOptionsMenu(Menu menu) {
562
        // Inflate the menu; this adds items to the action bar if it is present.
563
        getMenuInflater().inflate(R.menu.drawer, menu);
564
        return true;
565
    }
566
 
567
 
568
 
569
 
570
      /**
571
         * Create a new dummy account for the sync adapter
572
         *
573
         * @param context The application context
574
         */
575
    public static Account CreateSyncAccount(Context context) {
576
        // Create the account type and default account
577
        Account newAccount = new Account(
578
                Constants.ACCOUNT, Constants.ACCOUNT_TYPE);
579
        // Get an instance of the Android account manager
580
        AccountManager accountManager =
581
                (AccountManager) context.getSystemService(
582
                        ACCOUNT_SERVICE);
583
        /*
584
         * Add the account and account type, no password or user data
585
         * If successful, return the Account object, otherwise report an error.
586
         */
587
        if (accountManager.addAccountExplicitly(newAccount, null, null)) {
588
            /*
589
             * If you don't set android:syncable="true" in
590
             * in your <provider> element in the manifest,
591
             * then call context.setIsSyncable(account, AUTHORITY, 1)
592
             * here.
593
             */
594
 
595
            ContentResolver.setIsSyncable(newAccount, Constants.AUTHORITY, 1);
596
            ContentResolver.setSyncAutomatically(newAccount, Constants.AUTHORITY, true);
597
            ContentResolver.addPeriodicSync(newAccount,
598
                    Constants.AUTHORITY,  Bundle.EMPTY, Constants.SYNC_INTERVAL);
599
 
600
 
601
        } else {
602
            /*
603
             * The account exists or some other error occurred. Log this, report it,
604
             * or handle it internally.
605
             */
606
 
607
            Account[] accounts = accountManager.getAccounts();
608
            if(accounts != null && accounts.length > 0) {
609
 
610
                for(Account account : accounts)
611
                {
612
                    if(account.type.equals(Constants.ACCOUNT_TYPE)) {
613
                        return account;
614
                    }
615
                }
616
                return accounts[0];
617
            } else {
618
                return null;
619
            }
620
 
621
 
622
 
623
        }
624
 
625
        return newAccount;
626
 
627
 
628
    }
629
 
630
 
631
 
632
 
633
 
634
    @Override
635
    public void createSyncRecordNewToken(String token)
636
    {
637
 
638
        preference.setDeviceToken (token);
639
        preference.save(this);
640
 
641
        if(!TextUtils.isEmpty(preference.getDeviceUuid())) {
642
            Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, token);
643
            mAppDatabase.getSyncDao().insert(sync);
644
        }
645
    }
646
 
647
 
648
 
649
 
650
    @Override
651
    public void executeFcmCommand(String command)
652
    {
653
 
654
        if (command.equals("signout")) {
655
            signout();
656
        }
657
    }
658
 
659
 
660
 
661
    @Override
662
    public void setConnectedInternet(Boolean isConnected)
663
    {
664
        connected = isConnected;
665
        textViewMessageNotConnection.setVisibility(isConnected ? View.INVISIBLE : View.VISIBLE);
666
    }
667
 
668
    @Override
669
    public boolean isConnectedInternet() {
670
        return connected;
671
    }
672
 
673
    @Override
674
    public void showMessageSnackBar(String message) {
675
        Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_LONG).show();
676
    }
677
 
678
 
679
    @Override
680
    public void showMessageSnackBarWithClose(String message) {
681
        final Snackbar snackBar = Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_INDEFINITE);
682
 
683
        snackBar.setAction(R.string.snackbar_close, new View.OnClickListener() {
684
            @Override
685
            public void onClick(View v) {
686
                // Call your action method here
687
                snackBar.dismiss();
688
            }
689
        });
690
        snackBar.show();
691
 
692
 
693
    }
694
 
695
    @Override
696
    public void onErrorFatal() {
697
 
698
 
699
        invokeFragment(Constants.IDX_FRAGMENT_SIGNIN);
700
    }
701
 
702
    @Override
703
    public void invokeFragment(int fragmentIdxActiveNuevo)
704
    {
705
        String fragmentKeyActual    = PREFIX_FRAG + preference.getFragmentIdxActive();
706
        String fragmentKeyNuevo 	= PREFIX_FRAG + fragmentIdxActiveNuevo;
707
        preference.setFragmentIdxActive(fragmentIdxActiveNuevo);
708
        preference.save(this);
709
 
710
        Fragment fragment;
711
        if(!fragmentKeyActual.equalsIgnoreCase(fragmentKeyNuevo)) {
712
            if(fragmentHashMap.containsKey(fragmentKeyActual)) {
713
                fragment = fragmentHashMap.get(fragmentKeyActual);
714
                if(fragment != null) {
715
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
716
                    fragmentTransaction.hide(fragment);
717
                    fragmentTransaction.commit();
718
                }
719
            }
720
        }
721
 
722
        boolean add = false;
723
        fragment = null;
724
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
725
        mDrawerToggle.setDrawerIndicatorEnabled(false);
726
 
727
 
728
        switch(fragmentIdxActiveNuevo) {
729
            case Constants.IDX_FRAGMENT_SIGNIN :
730
                getSupportActionBar().hide();
731
                 if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
732
                     fragment = fragmentHashMap.get(fragmentKeyNuevo);
733
                 } else {
734
                     add = true;
735
                     fragment = new SigninFragment();
736
                 }
737
                break;
738
 
739
            case Constants.IDX_FRAGMENT_TOPICS :
740
 
741
 
742
                getSupportActionBar().show();
743
                mDrawerToggle.setDrawerIndicatorEnabled(true);
744
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
745
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
746
                } else {
747
                    add = true;
748
                    fragment = new TopicFragment();
749
                }
750
                break;
751
 
4 gabriel 752
 
1 efrain 753
            case Constants.IDX_FRAGMENT_CAPSULES :
754
                getSupportActionBar().show();
755
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
756
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
757
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
758
                } else {
759
                    add = true;
760
                    fragment = new CapsuleFragment();
761
                }
762
                break;
763
 
764
            case Constants.IDX_FRAGMENT_SLIDES :
765
                getSupportActionBar().show();
766
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
767
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
768
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
769
                } else {
770
                    add = true;
771
                    fragment = new SlideFragment();
772
                }
773
                break;
774
 
775
            case Constants.IDX_FRAGMENT_GALLERY :
776
                getSupportActionBar().show();
777
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
778
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
779
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
780
                } else {
781
                    add = true;
782
                    fragment = new GalleryFragment();
783
                }
784
 
785
                break;
786
 
787
            case Constants.IDX_FRAGMENT_FINISH_CAPSULE :
788
                getSupportActionBar().hide();
789
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
790
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
791
                } else {
792
                    add = true;
793
                    fragment = new FinishCapsuleFragment();
794
                }
795
                break;
4 gabriel 796
 
1 efrain 797
            case Constants.IDX_FRAGMENT_FINISH_TOPIC :
798
                getSupportActionBar().hide();
799
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
800
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
801
                } else {
802
                    add = true;
803
                    fragment = new FinishTopicFragment();
804
                }
805
                break;
806
 
807
            case Constants.IDX_FRAGMENT_TIMELINE :
808
                getSupportActionBar().show();
809
                mDrawerToggle.setDrawerIndicatorEnabled(true);
810
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
811
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
812
                } else {
813
                    add = true;
814
                    fragment = new TimelineFragment();
815
                }
816
                break;
817
 
818
            case Constants.IDX_FRAGMENT_COMPANIES:
819
                getSupportActionBar().show();
820
                mDrawerToggle.setDrawerIndicatorEnabled(true);
821
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
822
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
823
                } else {
824
                    add = true;
825
                    fragment = new CompanyFragment();
826
                }
827
                break;
828
 
829
            case Constants.IDX_FRAGMENT_PROGRESS :
830
                getSupportActionBar().show();
831
                mDrawerToggle.setDrawerIndicatorEnabled(true);
832
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
833
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
834
                } else {
835
                    add = true;
836
                    fragment = new ProgressFragment();
837
                }
838
                break;
839
 
840
            case Constants.IDX_FRAGMENT_USER_PROFILE:
841
                getSupportActionBar().show();
842
                mDrawerToggle.setDrawerIndicatorEnabled(true);
843
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
844
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
845
                } else {
846
                    add = true;
847
                    fragment = new UserProfileFragment();
848
                }
849
                break;
850
 
851
            default :
852
                getSupportActionBar().hide();
853
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
854
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
855
                } else {
856
                    add = true;
857
                    fragment = new IntroFragment();
858
                }
859
                break;
860
 
861
 
862
        }
863
 
864
        if(add) {
865
            fragmentHashMap.put(fragmentKeyNuevo, fragment);
866
 
867
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
868
            fragmentTransaction.add(R.id.fragment_container, fragment, fragmentKeyNuevo);
869
            fragmentTransaction.commit();
870
        }
871
 
872
 
873
        if(fragment != null) {
874
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
875
            fragmentTransaction.show(fragment);
876
            fragmentTransaction.commit();
877
        }
878
 
879
    }
880
 
881
    @Override
882
    public void changeTopicActive(String topicUuid)
883
    {
884
        Log.d(TAG, "changeTopicActive : " + topicUuid);
16 gabriel 885
       // Log.e("Guardo", "Topico en Main");
1 efrain 886
 
887
        preference.setTopicUuidActive(topicUuid);
888
        preference.setCapsuleUuidActive("");
889
        preference.setSlideUuidActive("");
890
        preference.save(this);
891
 
892
        invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
893
    }
894
 
895
    @Override
896
    public void changeCapsuleActive(String capsuleUuid)
897
    {
898
        Log.d(TAG, "changeCapsuleActive : " + capsuleUuid);
899
 
900
 
8 gabriel 901
 
1 efrain 902
        preference.setCapsuleUuidActive(capsuleUuid);
903
        preference.setSlideUuidActive("");
904
 
905
 
906
        preference.save(this);
907
 
908
        invokeFragment(Constants.IDX_FRAGMENT_SLIDES);
909
    }
910
 
911
    @Override
912
    public void changeCompanyActive(String companyUuid)
913
    {
914
        Log.d(TAG, "changeCompanyActive : " + companyUuid);
915
 
916
        preference.setCompanyUuidActive(companyUuid);
917
        preference.save(this);
918
    }
919
 
920
    @Override
921
    public void changeSlideActive(String slideUuid, String type, boolean showGallery)
922
    {
923
 
924
        Log.d(TAG, "changeSlideActive : " + slideUuid);
925
 
926
        if(!preference.getSlideUuidActive().equals(slideUuid) && type.equals(Constants.SLIDE_TYPE_IMAGE)) {
927
            Log.d(TAG, "registerOnPageChangeCallback - createProgressAndSyncRecord");
928
 
929
            createProgressAndSyncRecord(slideUuid, true, false, false);
930
        }
931
 
932
 
933
 
934
        preference.setSlideUuidActive(slideUuid);
935
        preference.save(this);
936
 
937
 
938
        if(showGallery) {
939
            invokeFragment(Constants.IDX_FRAGMENT_GALLERY);
8 gabriel 940
            Log.e("Aqui","Es donde cambio el capsule");
941
            DatabaseHelper.CambioSlide="SI";
1 efrain 942
        }
943
    }
944
 
945
    @Override
946
    public String getTopicUuidActive()
947
    {
948
        return preference.getTopicUuidActive();
949
    }
950
 
951
    @Override
952
    public String getCapsuleUuidActive()
953
    {
954
        return preference.getCapsuleUuidActive();
955
    }
956
 
957
    @Override
958
    public String getSlideUuidActive()
959
    {
960
        return preference.getSlideUuidActive();
961
    }
962
 
963
    @Override
964
    public String getCompanyUuidActive()
965
    {
966
        return preference.getCompanyUuidActive();
967
    }
968
 
969
    @Override
970
    public void setTitleActionBar(String title)
971
    {
972
        getSupportActionBar().setTitle(title);
973
    }
974
 
975
    @Override
976
    public synchronized void createProgressAndSyncRecord(String slideUuid, boolean completed, boolean isQuiz, boolean isAudioOrVideo)
977
    {
978
        Calendar calendar = Calendar.getInstance();
979
        Date date = calendar.getTime();
980
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
981
        String  dateOn = simpleDateFormat.format(date);
982
 
983
        SlideDao slideDao = mAppDatabase.getSlideDao();
984
        Slide slide =  slideDao.selectByUuid(slideUuid);
985
 
986
        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
987
        Capsule capsule = capsuleDao.selectByUuid(slide.getCapsuleUuid());
988
 
989
        TopicDao topicDao = mAppDatabase.getTopicDao();
990
        Topic topic = topicDao.selectByUuid(capsule.getTopicUuid());
991
 
992
        UserLog userLog;
993
        UserLogDao userLogDao = mAppDatabase.getUserLogDao();
994
 
995
        SyncDao syncDao = mAppDatabase.getSyncDao();
996
        Sync sync;
997
 
998
        // Progreso y UserLog  del Slide
999
        ProgressDao progressDao = mAppDatabase.getProgressDao();
1000
        Progress progressSlide = progressDao.selectBySlideUuid(slide.getUuid());
1001
        Progress progressCapsule =  progressDao.selectByCapsuleUuid(slide.getCapsuleUuid());
1002
        Progress progressTopic =  progressDao.selectByTopicUuid(slide.getTopicUuid());
1003
 
1004
        int totalSlides = 0;
1005
        int viewSlides = 0;
1006
        double percentaje = 0;
1007
        boolean newRecord = false;
1008
        boolean retakeQuiz = false;
1009
 
1010
        /*** INICIO PROCESO DIAPOSITIVA ***/
1011
        if(progressSlide == null) {
1012
 
1013
            retakeQuiz = false;
1014
 
1015
 
1016
            progressSlide = new Progress();
1017
            progressSlide.setUserUuid(preference.getUserUuid());
1018
            progressSlide.setCompanyUuid(topic.getCompanyUuid());
1019
            progressSlide.setTopicUuid(topic.getUuid());
1020
            progressSlide.setCapsuleUuid(capsule.getUuid());
1021
            progressSlide.setSlideUuid(slide.getUuid());
1022
            progressSlide.setType(Constants.PROGERSS_TYPE_SLIDE);
1023
            progressSlide.setCompleted(completed ? 1 : 0);
1024
            progressSlide.setAddedOn(dateOn);
1025
            progressSlide.setUpdatedOn(dateOn);
1026
            progressDao.insert(progressSlide);
1027
        } else {
1028
            retakeQuiz = true;
1029
 
1030
            if (progressSlide.getCompleted() == 1) {
1031
                progressSlide.setReturningAfterCompleted(progressSlide.getReturningAfterCompleted() + 1);
1032
            } else {
1033
                if (completed) {
4 gabriel 1034
                    //0 y 1 para Boolean
1 efrain 1035
                    progressSlide.setCompleted(completed  ? 1 : 0);
1036
                } else {
1037
                    progressSlide.setReturning(progressSlide.getReturning() + 1);
1038
                }
1039
            }
1040
 
1041
            progressSlide.setUpdatedOn(dateOn);
1042
            progressDao.update(progressSlide);
1043
        }
1044
 
1045
 
1046
        /*** FIN PROCESO DIAPOSITIVA ***/
1047
 
1048
 
1049
 
1050
        /*** INICIO PROCESO TOPICO ***/
1051
        ResultCount resultCount;
1052
 
1053
 
1054
        resultCount = slideDao.getCountByTopicUuid(slide.getTopicUuid());
1055
        totalSlides = resultCount.getCount();
1056
 
1057
        resultCount = progressDao.getCountSlidesCompletedByTopicUuid(slide.getTopicUuid());
1058
        viewSlides =  resultCount.getCount();
1059
        if(totalSlides == 0) {
1060
            percentaje = 0;
1061
        } else {
1062
            percentaje = (viewSlides * 100) / totalSlides;
1063
        }
1064
 
1065
        if(progressTopic == null) {
1066
            newRecord = true;
1067
            progressTopic = new Progress();
1068
            progressTopic.setUserUuid(preference.getUserUuid());
1069
            progressTopic.setCompanyUuid( topic.getCompanyUuid());
1070
            progressTopic.setTopicUuid (topic.getUuid());
1071
 
1072
            progressTopic.setViewSlides(viewSlides);
1073
            progressTopic.setTotalSlides(totalSlides);
1074
            progressTopic.setProgress (percentaje);
1075
            progressTopic.setType(Constants.PROGERSS_TYPE_TOPIC);
1076
 
1077
            progressTopic.setAddedOn(dateOn);
1078
            progressTopic.setUpdatedOn(dateOn);
1079
             progressDao.insert(progressTopic);
1080
        } else {
1081
            newRecord = false;
1082
            progressTopic.setViewSlides(viewSlides);
1083
            progressTopic.setTotalSlides(totalSlides);
1084
            progressTopic.setProgress (percentaje);
1085
            progressDao.update(progressTopic);
1086
        }
1087
 
1088
        try {
1089
            JSONObject json = progressTopic.toJson();
1090
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1091
 
1092
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1093
            syncDao.insert(sync);
1094
        } catch (JSONException e) {
1095
        }
1096
 
1097
        if(newRecord) {
1098
            userLog = new UserLog();
1099
            userLog.setUserUuid(preference.getUserUuid());
1100
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_TOPIC);
1101
            userLog.setCompanyUuid (topic.getCompanyUuid());
1102
            userLog.setTopicUuid (topic.getUuid());
1103
            userLog.setAddedOn(dateOn);
1104
 
1105
 
1106
            userLogDao.insert(userLog);
1107
            try {
1108
                JSONObject json = userLog.toJson();
1109
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1110
 
1111
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1112
                syncDao.insert(sync);
1113
            } catch (JSONException e) {
1114
            }
1115
        }
1116
        /*** FIN PROCESO TOPICO ***/
1117
 
1118
 
1119
 
1120
        /*** INICIO PROCESO CAPSULA ***/
1121
        resultCount = slideDao.getCountByCapsuleUuid(slide.getCapsuleUuid());
1122
        totalSlides = resultCount.getCount();
1123
        resultCount = progressDao.getCountSlidesCompletedByCapsuleUuid(slide.getCapsuleUuid());
1124
        viewSlides =  resultCount.getCount();
1125
        if(totalSlides == 0) {
1126
            percentaje = 0;
1127
        } else {
1128
            percentaje = (viewSlides * 100) / totalSlides;
1129
        }
1130
 
1131
        if(progressCapsule == null) {
1132
            newRecord = true;
1133
            progressCapsule = new Progress();
1134
            progressCapsule.setUserUuid(preference.getUserUuid());
1135
            progressCapsule.setCompanyUuid(topic.getCompanyUuid());
1136
            progressCapsule.setTopicUuid(topic.getUuid());
1137
            progressCapsule.setCapsuleUuid (capsule.getUuid());
1138
            progressCapsule.setViewSlides(viewSlides);
1139
            progressCapsule.setTotalSlides(totalSlides);
1140
            progressCapsule.setProgress(percentaje);
1141
            progressCapsule.setType(Constants.PROGERSS_TYPE_CAPSULE);
1142
            progressCapsule.setAddedOn(dateOn);
1143
            progressCapsule.setUpdatedOn(dateOn);
1144
            progressDao.insert(progressCapsule);
1145
 
1146
            Log.d(TAG, "Progress Capsule Nueva : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1147
            preference.setLastCapsuleUuidActive(capsule.getUuid());
1148
        } else {
1149
            newRecord = false;
1150
            progressCapsule.setViewSlides(viewSlides);
1151
            progressCapsule.setTotalSlides(totalSlides);
1152
            progressCapsule.setProgress(percentaje);
1153
 
1154
            Log.d(TAG, "Progress Capsule : getLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1155
            Log.d(TAG, "Progress Capsule : CapsuleActive : " + preference.getCapsuleUuidActive());
1156
 
1157
            if (!preference.getLastCapsuleUuidActive().equals(preference.getCapsuleUuidActive())) {
1158
 
1159
                Log.d(TAG, "Capsule Progress : " + progressCapsule.getProgress());
1160
                Log.d(TAG, "Capsule Completed : " + progressCapsule.getCompleted());
1161
                Log.d(TAG, "Capsule Total slides : " + progressCapsule.getTotalSlides());
1162
                Log.d(TAG, "Capsule View slides : " + progressCapsule.getViewSlides());
1163
 
1164
                if(progressCapsule.getCompleted() == 1) {
1165
                    Log.d(TAG, "Capsule OLD returningAfterCompleted = " + progressCapsule.getReturningAfterCompleted());
1166
 
1167
                    int returningAfterCompleted = progressCapsule.getReturningAfterCompleted() + 1;
1168
 
1169
                    Log.d(TAG, "Capsule NEW returningAfterCompleted = " + returningAfterCompleted);
1170
                    progressCapsule.setReturningAfterCompleted(returningAfterCompleted);
1171
                }
1172
 
1173
                preference.setLastCapsuleUuidActive(capsule.getUuid());
1174
                preference.save(this);
1175
 
1176
                Log.d(TAG, "Progress Capsule : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1177
            }
1178
 
1179
            progressDao.update(progressCapsule);
1180
        }
1181
        try {
1182
            JSONObject json = progressCapsule.toJson();
1183
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1184
 
1185
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1186
            syncDao.insert(sync);
1187
        } catch (JSONException e) {
1188
 
1189
        }
1190
 
1191
        if(newRecord) {
1192
            userLog = new UserLog();
1193
            userLog.setUserUuid(preference.getUserUuid());
1194
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_CAPSULE);
1195
            userLog.setCompanyUuid(topic.getCompanyUuid());
1196
            userLog.setTopicUuid(topic.getUuid());
1197
            userLog.setCapsuleUuid(capsule.getUuid());
1198
            userLog.setAddedOn(dateOn);
1199
 
1200
 
1201
            userLogDao.insert(userLog);
1202
            try {
1203
                JSONObject json = userLog.toJson();
1204
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1205
 
1206
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1207
                syncDao.insert(sync);
1208
            } catch (JSONException e) {
1209
            }
1210
        }
1211
 
1212
 
1213
        /*** FIN PROCESO CAPSULA ***/
1214
 
1215
        /*** INICIO USERLOG SLIDE ***/
1216
        userLog = new UserLog();
1217
        userLog.setUserUuid(preference.getUserUuid());
1218
        userLog.setActivity(Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1219
        userLog.setCompanyUuid(topic.getCompanyUuid());
1220
        userLog.setTopicUuid(topic.getUuid());
1221
        userLog.setCapsuleUuid(capsule.getUuid());
1222
        userLog.setSlideUuid(slide.getUuid());
1223
        userLog.setAddedOn(dateOn);
1224
 
1225
 
1226
        userLogDao.insert(userLog);
1227
        try {
1228
            JSONObject json = userLog.toJson();
1229
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1230
 
1231
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1232
            syncDao.insert(sync);
1233
        } catch (JSONException e) {
1234
        }
1235
 
1236
        /*** FIN ***/
1237
 
1238
 
1239
        /*** PROGRESS SLIDE***/
1240
        try {
1241
            JSONObject json = progressSlide.toJson();
1242
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1243
 
1244
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1245
            syncDao.insert(sync);
1246
        } catch (JSONException e) {
1247
        }
1248
 
1249
        /** IS SLIDE = QUIZ **/
1250
        if (isQuiz) {
1251
            userLog = new UserLog();
1252
            userLog.setUserUuid(preference.getUserUuid());
1253
            userLog.setActivity(retakeQuiz ? Constants.USER_LOG_ACTIVITY_RETAKE_A_TEST : Constants.USER_LOG_ACTIVITY_TAKE_A_TEST);
1254
            userLog.setCompanyUuid (topic.getCompanyUuid());
1255
            userLog.setTopicUuid(slide.getTopicUuid());
1256
            userLog.setCapsuleUuid(slide.getCapsuleUuid());
1257
            userLog.setSlideUuid(slide.getUuid());
1258
            userLog.setAddedOn(dateOn);
1259
 
1260
            userLogDao.insert(userLog);
1261
            try {
1262
                JSONObject json = userLog.toJson();
1263
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1264
 
1265
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1266
                syncDao.insert(sync);
1267
            } catch (JSONException e) {
1268
            }
1269
 
1270
 
1271
            if(progressSlide.getCompleted() == 1) {
1272
                userLog = new UserLog();
1273
                userLog.setUserUuid(preference.getUserUuid());
1274
                userLog.setActivity(Constants.USER_LOG_ACTIVITY_APPROVED_TEST);
1275
                userLog.setCompanyUuid(topic.getCompanyUuid());
1276
                userLog.setTopicUuid(slide.getTopicUuid());
1277
                userLog.setCapsuleUuid(slide.getCapsuleUuid());
1278
                userLog.setSlideUuid(slide.getUuid());
1279
                userLog.setAddedOn(dateOn);
1280
 
1281
                userLogDao.insert(userLog);
1282
                try {
1283
                    JSONObject json = userLog.toJson();
1284
                    json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1285
 
1286
                    sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1287
                    syncDao.insert(sync);
1288
                } catch (JSONException e) {
1289
                }
1290
 
1291
            } else {
1292
                if(progressSlide.getCompleted() == 1) {
1293
                    userLog = new UserLog();
1294
                    userLog.setUserUuid(preference.getUserUuid());
1295
                    userLog.setActivity( Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1296
                    userLog.setCompanyUuid(topic.getCompanyUuid());
1297
                    userLog.setTopicUuid(slide.getTopicUuid());
1298
                    userLog.setCapsuleUuid(slide.getCapsuleUuid());
1299
                    userLog.setSlideUuid(slide.getUuid());
1300
                    userLog.setAddedOn(dateOn);
1301
 
1302
                    userLogDao.insert(userLog);
1303
                    try {
1304
                        JSONObject json = userLog.toJson();
1305
                        json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1306
 
1307
                        sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1308
                        syncDao.insert(sync);
1309
                    } catch (JSONException e) {
1310
                    }
1311
                }
1312
            }
1313
        }
1314
 
1315
        requestExecuteSyncAdapter();
1316
    }
1317
 
1318
    @Override
1319
    public void launchVideoViewer(String videoAudioUrl)
1320
    {
1321
 
1322
        Intent intent = new Intent(this, VideoAudioActivity.class);
1323
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1324
        intent.putExtra("deviceId", preference.getDeviceUuid());
1325
        intent.putExtra("password", preference.getPassword());
1326
        //startActivityForResult(intent, Constants.REQUEST_CODE_VIDEO);
1327
 
1328
        mLauncher.launch(intent);
1329
 
1330
    }
1331
 
1332
    @Override
1333
    public void launchAudioViewer(String videoAudioUrl)
1334
    {
1335
 
1336
        Intent intent = new Intent(this, VideoAudioActivity.class);
1337
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1338
        intent.putExtra("deviceId", preference.getDeviceUuid());
1339
        intent.putExtra("password", preference.getPassword());
1340
        //startActivityForResult(intent, Constants.REQUEST_CODE_AUDIO);
1341
 
1342
 
1343
        mLauncher.launch(intent);
1344
    }
1345
 
1346
    @Override
1347
    public void launchTextViewer(String description)
1348
    {
1349
        Intent intent = new Intent(this,TextActivity.class);
1350
        intent.putExtra("description",description);
1351
 
1352
        //startActivityForResult(intent, Constants.REQUEST_CODE_TEXT);
1353
 
1354
        mLauncher.launch(intent);
1355
    }
1356
 
1357
 
1358
    @Override
1359
    public void launchDocumentViewer(String file)
1360
    {
1361
 
1362
        Intent intent = new Intent(this,PdfActivity.class);
1363
        intent.putExtra("documentUrl",file);
1364
        intent.putExtra("deviceId", preference.getDeviceUuid());
1365
        intent.putExtra("password", preference.getPassword());
1366
 
1367
        //startActivityForResult(intent, Constants.REQUEST_CODE_PDF);
1368
 
1369
        mLauncher.launch(intent);
1370
    }
1371
 
1372
    @Override
1373
    public void launchQuizViewer(String quizUuid)
1374
    {
1375
        ProgressDao progressDao = mAppDatabase.getProgressDao();
1376
        Progress progress = progressDao.selectBySlideUuid(preference.getSlideUuidActive());
1377
 
1378
        boolean launch = false;
1379
        if(progress != null && progress.getCompleted() == 0) {
1380
 
1381
            Calendar calendar = Calendar.getInstance();
1382
            Date date = calendar.getTime();
1383
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1384
            try {
1385
                Long updateOn = simpleDateFormat.parse(progress.getUpdatedOn()).getTime();
1386
 
1387
                //30 minutes
1388
                long mintime = 30 * 60 * 1000;
1389
                if(date.getTime() - updateOn >  mintime ) {
1390
                    launch = true;
1391
                }
1392
 
1393
                launch = true;
1394
 
1395
            } catch(Exception e) {
1396
 
1397
            }
1398
 
1399
 
1400
        } else {
1401
            launch = true;
1402
        }
1403
 
1404
        if(launch) {
1405
 
1406
            QuizDao quizDao = mAppDatabase.getQuizDao();
1407
            Quiz quiz = quizDao.selectByUuid(quizUuid);
1408
 
1409
            TopicDao topicDao = mAppDatabase.getTopicDao();
1410
            Topic topic = topicDao.selectByUuid(preference.getTopicUuidActive());
1411
 
1412
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1413
            Capsule capsule = capsuleDao.selectByUuid(preference.getCapsuleUuidActive());
1414
 
1415
            SlideDao slideDao = mAppDatabase.getSlideDao();
1416
            Slide slide = slideDao.selectByUuid(preference.getSlideUuidActive());
1417
 
1418
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1419
            List<Question> questions = questionDao.selectAllByQuizUuid(quiz.getUuid());
1420
 
1421
 
1422
            List<Answer> answers;
1423
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1424
 
1425
            Intent intent = new Intent(this, QuizActivity.class);
1426
           // intent.putExtra("companyUuid", topic.getCompanyUuid());
1427
           // intent.putExtra("topicUuid", topic.getUuid());
1428
            //intent.putExtra("capsuleUuid", capsule.getUuid());
1429
            //intent.putExtra("slideUuid", slide.getUuid());
1430
            //intent.putExtra("userUuid", preference.getUserUuid());
1431
            //intent.putExtra("quizUuid", quizUuid);
1432
 
1433
 
1434
            intent.putExtra("quiz_uuid", quiz.getUuid());
1435
            intent.putExtra("quiz_company_uuid", quiz.getCompanyUuid());
1436
            intent.putExtra("quiz_name", quiz.getName());
1437
            intent.putExtra("quiz_points", quiz.getPoints());
1438
            intent.putExtra("quiz_max_time", quiz.getMaxTime());
1439
            intent.putExtra("quiz_minimum_points_required", quiz.getMinimumPointsRequired());
1440
            intent.putExtra("quiz_failed", quiz.getFailed());
1441
            intent.putExtra("quiz_text", quiz.getText());
1442
 
1443
            intent.putExtra("questions", questions.size());
1444
            int i = 1;
1445
            int j = 1;
1446
            for(Question question : questions) {
1447
                intent.putExtra("question" + i + "_uuid", question.getUuid());
1448
                intent.putExtra("question" + i + "_text", question.getText());
1449
                intent.putExtra("question" + i + "_max_length", question.getMaxlength());
1450
                intent.putExtra("question" + i + "_position", question.getPosition());
1451
                intent.putExtra("question" + i + "_points", question.getPoints());
1452
                intent.putExtra("question" + i + "_type", question.getType());
1453
 
1454
                answers = answerDao.selectAllByQuestionUuid(question.getUuid());
1455
                intent.putExtra("question" + i + "_answers", answers.size());
1456
 
1457
                j = 1;
1458
                for(Answer answer : answers) {
1459
                    intent.putExtra("question" + i + "_answer_uuid" + j, answer.getUuid());
1460
                    intent.putExtra("question" + i + "_answer_text" + j, answer.getText());
1461
                    intent.putExtra("question" + i + "_answer_points" + j, answer.getPoints());
1462
                    intent.putExtra("question" + i + "_answer_correct" + j, answer.getCorrect());
1463
                    j++;
1464
                }
1465
 
1466
                i++;
1467
            }
1468
 
1469
 
1470
 
1471
            //startActivityForResult(intent, Constants.REQUEST_CODE_QUIZ);
1472
 
1473
            mLauncher.launch(intent);
1474
        } else {
1475
            showMessageSnackBar(getString(R.string.error_retry_quiz_min_time));
1476
        }
1477
    }
1478
 
1479
 
1480
    @Override
1481
    public Preference getPreference() {
1482
        return preference;
1483
    }
1484
 
1485
    @Override
1486
    public Preference reloadPreference()
1487
    {
1488
        preference = new Preference(this);
1489
        return preference;
1490
    }
1491
 
1492
    @Override
1493
    public void reloadNavHeader() {
1494
        Log.d(TAG, "User Image = " + preference.getImage());
1495
        navHeaderUserName.setText((preference.getFirstName() + " " + preference.getLastName()).trim());
1496
        navHeaderUserEmail.setText(preference.getEmail());
1497
 
1498
 
1499
 
1500
        Log.d(TAG, preference.getImage());
1501
        if(!TextUtils.isEmpty(preference.getImage())) {
1502
 
1503
            TimeZone timeZone = TimeZone.getTimeZone("UTC");
1504
            Calendar calendar = Calendar.getInstance(timeZone);
1505
            TimeZone tz = calendar.getTimeZone();
1506
            int created =  (int) (calendar.getTimeInMillis() / 1000);
1507
 
1508
            Random random = new Random(created);
1509
            int rand = 1000 + random.nextInt(8999);
1510
 
1511
 
1512
 
1513
 
1514
            Log.d(TAG, "token = " + preference.getDeviceUuid());
1515
            Log.d(TAG, "created = " + created);
1516
            Log.d(TAG, "rand = " + rand);
1517
            Log.d(TAG, "calc = " + preference.getPassword() + ':' +  created + ':' + rand);
1518
 
1519
            String secret = MD5.generar(preference.getPassword() + ':' +  created + ':' + rand);
1520
 
1521
            GlideUrl url = new GlideUrl(preference.getImage(), new LazyHeaders.Builder()
1522
                    .addHeader(Constants.HTTP_HEADER_ACCEPT, Constants.HTTP_HEADER_ACCEPT_VALUE)
1523
                    .addHeader(Constants.HTTP_HEADER_SECURITY_TOKEN, preference.getDeviceUuid())
1524
                    .addHeader(Constants.HTTP_HEADER_SECURITY_SECRET, secret)
1525
                    .addHeader(Constants.HTTP_HEADER_SECURITY_CREATED, String.valueOf(created))
1526
                    .addHeader(Constants.HTTP_HEADER_SECURITY_RAND, String.valueOf(rand))
1527
                    .build());
1528
 
1529
            RequestOptions options = new RequestOptions()
1530
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
1531
 
1532
            Glide.with(this).load(url)
1533
                    .thumbnail()
1534
                    .apply(options)
1535
                    .into(navHeaderUserImage);
1536
        }
1537
    }
1538
 
1539
    public void requestCheckChanges()
1540
    {
1541
        Log.d(TAG, "requestCheckChanges");
1542
        try {
1543
 
1544
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1545
            List<Capsule> capsules = capsuleDao.selectAll();
1546
 
1547
            if(capsules.size() > 0) {
1548
                //ArrayList<String> ids = new ArrayList<>();
1549
 
1550
                TimeZone timeZone = TimeZone.getTimeZone("UTC");
1551
                Calendar calendar = Calendar.getInstance(timeZone);
1552
                TimeZone tz = calendar.getTimeZone();
1553
                int created =  (int) (calendar.getTimeInMillis() / 1000);
1554
 
1555
                Random random = new Random(created);
1556
                int rand = 1000 + random.nextInt(8999);
1557
 
1558
 
1559
                //Log.d("requestCheckChanges", "token = " + preference.getDeviceUuid());
1560
                //Log.d("requestCheckChanges", "created = " + created);
1561
               // Log.d("requestCheckChanges", "rand = " + rand);
1562
                //Log.d("requestCheckChanges", "calc = " + preference.password + ':' +  created + ':' + rand);
1563
 
1564
                String secret = MD5.generar(preference.getPassword() + ':' +  created + ':' + rand);
1565
 
1566
                //Log.d("requestCheckChanges", "secret = " + secret);
1567
 
1568
 
1569
                FormBody.Builder formBodyCheckChangeBuilder = new FormBody.Builder();
1570
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_DEVICE_UUID, preference.getDeviceUuid());
1571
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_DATE_CHANGES, preference.getMaxDateChanges());
1572
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_IS_FOREGROUND, String.valueOf(isForeground ? 1 : 0));
1573
                Http http = new Http(this.getCacheDir(), preference.getDeviceUuid(), secret, created, rand);
1574
                OkHttpClient client = http.getHttpClient(false);
1575
 
1576
 
1577
 
1578
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(capsules.size()));
1579
                //formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(0));
1580
 
1581
              int i = 1;
1582
                for(Capsule capsule : capsules)
1583
                {
1584
                    Log.d("requestCheckChanges", "id" + i + " = " + capsule.getTopicUuid() + "|" + capsule.getUuid());
1585
 
1586
 
1587
                    formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_ID + i, capsule.getTopicUuid() + "|" + capsule.getUuid());
1588
                    i++;
1589
                }
1590
 
1591
 
1592
 
1593
                RequestBody formBody = formBodyCheckChangeBuilder.build();
1594
 
1595
                Log.d(TAG, "URL = " + Configuration.URL_CHECK_CHANGES);
1596
                Request request = new Request.Builder()
1597
                        .url(Configuration.URL_CHECK_CHANGES)
1598
                        .post(formBody)
1599
                        .build();
1600
 
1601
                Call call = client.newCall(request);
1602
                call.enqueue(new okhttp3.Callback() {
1603
                    public void onResponse(Call call, Response response)
1604
                            throws IOException {
1605
 
1606
 
1607
 
1608
                        processResponseServerChanges(response.body().string());
1609
                    }
1610
 
1611
                    public void onFailure(Call call, IOException e) {
1612
                        Log.d(TAG, "Error :  " +  e.getMessage());
1613
                    }
1614
                });
1615
            }
1616
 
1617
 
1618
 
1619
        } catch(Exception e) {
1620
 
1621
        }
1622
    }
1623
 
1624
 
1625
    public void syncFromServer(JSONObject data)
1626
    {
1627
        try {
1628
            JSONObject objUser = data.getJSONObject("user");
1629
            String userUuid = objUser.getString("uuid");
1630
 
1631
 
1632
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1633
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1634
            QuizDao quizDao = mAppDatabase.getQuizDao();
1635
            SlideDao slideDao = mAppDatabase.getSlideDao();
1636
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1637
            TopicDao topicDao = mAppDatabase.getTopicDao();
1638
            CompanyDao companyDao = mAppDatabase.getCompanyDao();
1639
            UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
1640
 
1641
 
1642
 
1643
            ProgressDao progressDao = mAppDatabase.getProgressDao();
1644
            progressDao.removeAllUserUuidNotEqual(userUuid);
1645
 
1646
 
1647
            UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1648
            userLogDao.removeAllUserUuidNotEqual(userUuid);
1649
 
1650
            JSONArray arrayCapsules;
1651
            JSONArray arraySlides;
1652
            JSONArray arrayAnswers;
1653
            JSONArray arrayQuestions;
1654
            JSONArray arrayProgress;
1655
            JSONArray arrayQuizzes;
1656
            JSONArray arrayUserLog;
1657
 
1658
            JSONObject objTopic;
1659
            JSONObject objCapsule;
1660
            JSONObject objSlide;
1661
            JSONObject objAnswer;
1662
            JSONObject objQuestion;
1663
            JSONObject objQuiz;
1664
            JSONObject objProgress;
1665
            JSONObject objUserLog;
1666
            int i,j,x;
1667
 
1668
            if(data.has("progress")) {
1669
 
1670
                arrayProgress = data.getJSONArray("progress");
1671
                for (i = 0; i < arrayProgress.length(); i++) {
1672
                    objProgress = arrayProgress.getJSONObject(i);
1673
 
1674
 
1675
                    Progress progress = null;
1676
 
1677
 
1678
                    userUuid = objProgress.getString("user_uuid");
1679
                    String type = objProgress.getString("type");
1680
                    String topicUuid = objProgress.getString("topic_uuid");
1681
                    String capsuleUuid = objProgress.getString("capsule_uuid");
1682
                    String slideUuid = objProgress.getString("slide_uuid");
1683
 
1684
                    if(type == Constants.PROGERSS_TYPE_SLIDE) {
1685
                        progress = progressDao.selectBySlideUuidAndUserUuid(slideUuid, userUuid);
1686
                    } else if(type == Constants.PROGERSS_TYPE_CAPSULE) {
1687
                        progress = progressDao.selectByCapsuleUuidAndUserUuid(capsuleUuid, userUuid);
1688
                    } else if(type == Constants.PROGERSS_TYPE_TOPIC) {
1689
                        progress = progressDao.selectByTopicUuidAndUserUuid(topicUuid, userUuid);
1690
                    }
1691
 
1692
 
1693
                    if(progress == null) {
1694
                        progress = new Progress();
1695
                        progress.setUserUuid(userUuid);
1696
                        progress.setCompanyUuid(objProgress.getString("company_uuid"));
1697
                        progress.setTopicUuid(topicUuid);
1698
                        progress.setCapsuleUuid(capsuleUuid);
1699
                        progress.setSlideUuid(slideUuid);
1700
                        progress.setProgress(objProgress.getDouble("progress"));
1701
                        progress.setTotalSlides(objProgress.getInt("total_slides"));
1702
                        progress.setViewSlides(objProgress.getInt("view_slides"));
1703
                        progress.setType(type);
1704
                        progress.setReturning(objProgress.getInt("returning"));
1705
                        progress.setReturningAfterCompleted(objProgress.getInt("returning_after_completed"));
1706
                        progress.setCompleted(objProgress.getInt("completed"));
1707
                        progress.setAddedOn(objProgress.getString("added_on"));
1708
                        progress.setUpdatedOn(objProgress.getString("updated_on"));
1709
 
1710
                        progressDao.insert(progress);
1711
                    }
1712
 
1713
 
1714
                }
1715
            }
1716
 
1717
            if(data.has("userlog")) {
1718
                arrayUserLog = data.getJSONArray("userlog");
1719
                for (i = 0; i < arrayUserLog.length(); i++) {
1720
                    objUserLog = arrayUserLog.getJSONObject(i);
1721
 
1722
                    userUuid = objUserLog.getString("user_uuid");
1723
                    String activity = objUserLog.getString("activity");
1724
                    String added_on = objUserLog.getString("added_on");
1725
 
1726
                    UserLog userLog = userLogDao.selectOneByUserUuidAndActivityAndAddedOn(userUuid, activity, added_on);
1727
                    if(userLog == null) {
1728
                        userLog = new UserLog();
1729
                        userLog.setUserUuid(objUserLog.getString("user_uuid"));
1730
                        userLog.setCompanyUuid(objUserLog.getString("company_uuid"));
1731
                        userLog.setTopicUuid(objUserLog.getString("topic_uuid"));
1732
                        userLog.setCapsuleUuid(objUserLog.getString("capsule_uuid"));
1733
                        userLog.setSlideUuid(objUserLog.getString("slide_uuid"));
1734
                        userLog.setActivity(objUserLog.getString("activity"));
1735
                        userLog.setAddedOn(objUserLog.getString("added_on"));
1736
                        userLogDao.insert(userLog);
1737
                    }
1738
                }
1739
            }
1740
 
1741
            if(data.has("quizzes")) {
1742
                arrayQuizzes = data.getJSONArray("quizzes");
1743
                for (i = 0; i < arrayQuizzes.length(); i++) {
1744
                    objQuiz = arrayQuizzes.getJSONObject(i);
1745
                    Quiz quiz = new Quiz();
1746
                    quiz.setUuid(  objQuiz.getString("uuid"));
1747
                    quiz.setCompanyUuid(  objQuiz.getString("company_uuid"));
1748
                    quiz.setFailed(  objQuiz.getString("failed"));
1749
                    quiz.setName(  objQuiz.getString("name"));
1750
                    quiz.setText(  objQuiz.getString("text"));
1751
                    quiz.setPoints(  objQuiz.getInt("points"));
1752
                    quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
1753
                    quiz.setMaxTime( objQuiz.getInt("max_time"));
1754
 
1755
                    Company company = companyDao.selectByUuid(quiz.getCompanyUuid());
1756
                    if (company == null) {
1757
                        company = new Company();
1758
                        company.setUuid(objQuiz.getString("company_uuid"));
1759
                        company.setName(objQuiz.getString("company_name"));
1760
                        company.setImage(objQuiz.getString("company_image"));
1761
 
1762
                        companyDao.insert(company);
1763
                    }
1764
 
1765
                    quizDao.insert(quiz);
1766
 
1767
                    arrayQuestions = objQuiz.getJSONArray("questions");
1768
                    for (j = 0; j < arrayQuestions.length(); j++) {
1769
                        objQuestion = arrayQuestions.getJSONObject(j);
1770
                        Question question = new Question();
1771
                        question.setQuizUuid( quiz.getUuid());
1772
                        question.setUuid( objQuestion.getString("uuid"));
1773
                        question.setText( objQuestion.getString("text"));
1774
                        question.setType( objQuestion.getString("type"));
1775
                        question.setPoints( objQuestion.getInt("points"));
1776
                        question.setMaxlength( objQuestion.getInt("maxlength"));
1777
 
1778
                        questionDao.insert(question);
1779
 
1780
                        arrayAnswers = objQuestion.getJSONArray("answers");
1781
                        for (x = 0; x < arrayAnswers.length(); x++) {
1782
                            objAnswer = arrayAnswers.getJSONObject(x);
1783
                            Answer answer = new Answer();
1784
                            answer.setQuestionUuid(question.getUuid());
1785
                            answer.setUuid(objAnswer.getString("uuid"));
1786
                            answer.setText(objAnswer.getString("text"));
1787
                            answer.setPoints( objAnswer.getInt("points"));
1788
                            answer.setCorrect(objAnswer.getString("correct"));
1789
 
1790
                            answerDao.insert(answer);
1791
                        }
1792
 
1793
 
1794
                    }
1795
                }
1796
            }
1797
 
1798
 
1799
 
1800
 
1801
 
1802
            if(data.has("topics")) {
1803
 
1804
                JSONArray arrayTopics = data.getJSONArray("topics");
1805
                for (i = 0; i < arrayTopics.length(); i++) {
1806
                    objTopic = arrayTopics.getJSONObject(i);
1807
                    Topic topic = new Topic();
1808
                    topic.setUuid(objTopic.getString("uuid"));
1809
                    topic.setCompanyUuid(objTopic.getString("company_uuid"));
1810
                    topic.setName(objTopic.getString("name"));
1811
                    topic.setDescription(objTopic.getString("description"));
1812
                    topic.setImage(objTopic.getString("image"));
1813
                    topic.setPosition(objTopic.getInt("position"));
1814
 
1815
                    Company company = companyDao.selectByUuid(topic.getCompanyUuid());
1816
                    if (company == null) {
1817
                        company = new Company();
1818
                        company.setUuid(objTopic.getString("company_uuid"));
1819
                        company.setName(objTopic.getString("company_name"));
1820
                        company.setImage(objTopic.getString("company_image"));
1821
 
1822
                        companyDao.insert(company);
1823
                    }
1824
 
1825
                    topicDao.insert(topic);
1826
 
1827
                    arrayCapsules = objTopic.getJSONArray("capsules");
1828
                    for (j = 0; j < arrayCapsules.length(); j++) {
1829
                        objCapsule = arrayCapsules.getJSONObject(j);
1830
                        Capsule capsule = new Capsule();
1831
                        capsule.setTopicUuid(topic.getUuid());
1832
                        capsule.setUuid(objCapsule.getString("uuid"));
1833
                        capsule.setName(objCapsule.getString("name"));
1834
                        capsule.setDescription(objCapsule.getString("description"));
1835
                        capsule.setImage(objCapsule.getString("image"));
1836
                        capsule.setPosition(objCapsule.getInt("position"));
1837
                        capsuleDao.insert(capsule);
1838
 
1839
                        arraySlides = objCapsule.getJSONArray("slides");
1840
                        for (x = 0; x < arraySlides.length(); x++) {
1841
                            objSlide = arraySlides.getJSONObject(x);
1842
                            Slide slide = new Slide();
1843
                            slide.setUuid(objSlide.getString("uuid"));
1844
                            slide.setTopicUuid(capsule.getTopicUuid());
1845
                            slide.setCapsuleUuid(capsule.getUuid());
1846
                            slide.setQuizUuid(objSlide.getString("quiz_uuid"));
1847
                            slide.setName(objSlide.getString("name"));
1848
                            slide.setDescription(objSlide.getString("description"));
1849
                            slide.setPosition(objSlide.getInt("position"));
1850
                            slide.setType(objSlide.getString("type"));
1851
                            slide.setFile(objSlide.getString("file"));
1852
                            slide.setBackground(objSlide.getString("background"));
1853
 
1854
                            slideDao.insert(slide);
1855
                        }
1856
 
1857
                    }
1858
 
1859
 
1860
                }
1861
            }
1862
 
1863
 
1864
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1865
            if(data.has("max_date_changes")) {
1866
                String max_date_changes = data.getString("max_date_changes");
1867
                Log.d("syncFromServer", "max_date_changes : " + max_date_changes);
1868
 
1869
                if(!TextUtils.isEmpty(max_date_changes)) {
1870
                    preference.setMaxDateChanges(max_date_changes);
1871
                }
1872
            } else {
1873
                Log.d("syncFromServer", "No max_date_changes");
1874
            }
1875
 
1876
            Calendar calendar = Calendar.getInstance();
1877
            Date date = calendar.getTime();
1878
 
1879
            String  addedOn = simpleDateFormat.format(date);
1880
 
1881
            List<Company> companies = mAppDatabase.getCompanyDao().selectAll();
1882
            int companySize = companies.size();
1883
 
1884
            if(companySize > 0) {
1885
 
1886
                if(TextUtils.isEmpty(preference.getCompanyUuidActive())) {
1887
 
1888
                    preference.setCompanyUuidActive(companies.get(0).getUuid());
1889
 
1890
                } else {
1891
 
1892
                    boolean companyExist = false;
1893
                    for (Company company : companies) {
1894
                        if (company.getUuid().equals(preference.getCompanyUuidActive())) {
1895
                            companyExist = true;
1896
                        }
1897
                    }
1898
 
1899
                    if(!companyExist) {
1900
                        preference.setCompanyUuidActive(companies.get(0).getUuid());
1901
                    }
1902
                }
1903
 
1904
            } else {
1905
                preference.setCompanyUuidActive("");
1906
            }
1907
 
1908
            if(data.has( "extended")) {
1909
 
1910
                JSONObject objExtended;
1911
                JSONObject objItem;
1912
                JSONArray objItems;
1913
 
1914
                String company_uuid;
1915
 
1916
                UserExtended userExtended;
1917
 
1918
                JSONArray extendedCompanies = data.getJSONArray("extended");
1919
                for(i = 0 ; i < extendedCompanies.length(); i++)
1920
                {
1921
                    objExtended = extendedCompanies.getJSONObject(i);
1922
                    if(objExtended.has("details")) {
1923
                        company_uuid = objExtended.getString("company_uuid");
1924
 
1925
                        objItems = objExtended.getJSONArray("details");
1926
                        for(j = 0 ; j < objItems.length(); j++) {
1927
                            objItem = objItems.getJSONObject(j);
1928
                            userExtended = new UserExtended();
1929
                            userExtended.setCompanyUuid(company_uuid);
1930
                            userExtended.setUuid(objItem.getString("uuid"));
1931
                            userExtended.setLabel(objItem.getString("label"));
1932
                            userExtended.setValue(objItem.getString("value"));
1933
                            userExtendedDao.insert(userExtended);
1934
 
1935
                        }
1936
                    }
1937
                }
1938
 
1939
            }
1940
 
1941
            preference.setLastDataRefresh(addedOn);
1942
            preference.setCompanyCount(companySize);
1943
            preference.save(this);
1944
 
1945
        } catch (JSONException e) {
1946
            Log.d(TAG, e.getMessage());
1947
        }
1948
    }
1949
 
1950
    @Override
1951
    public void requestExecuteSyncAdapter() {
1952
            // Pass the settings flags by inserting them in a bundle
1953
            Bundle settingsBundle = new Bundle();
1954
            settingsBundle.putBoolean(
1955
                    ContentResolver.SYNC_EXTRAS_MANUAL, true);
1956
            settingsBundle.putBoolean(
1957
                    ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
1958
 
1959
            ContentResolver.requestSync(mAccount, Constants.AUTHORITY, settingsBundle);
1960
    }
1961
 
1962
 
1963
    private void processResponseServerChanges(String dataString)
1964
    {
1965
 
1966
        Log.d(TAG, "processResponseServerChanges = " + dataString);
1967
 
1968
        try {
1969
            JSONObject objJSON = new JSONObject(dataString);
1970
            boolean success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
1971
 
1972
 
1973
            if(success) {
1974
                Calendar calendar = Calendar.getInstance();
1975
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1976
                preference.setLastDataRefresh(simpleDateFormat.format(calendar.getTime()));
1977
                preference.save(this);
1978
 
1979
                String max_date_changes = "";
1980
                boolean processChanges = false;
1981
 
1982
                JSONObject data = objJSON.getJSONObject("data");
1983
                if(data.has("max_date_changes") && data.has("new_capsules")) {
1984
                    int new_capsules = data.getInt("new_capsules");
1985
                    max_date_changes = data.getString("max_date_changes");
1986
 
1987
 
1988
 
1989
 
1990
                    processChanges = new_capsules > 0 && !max_date_changes.equals(preference.getMaxDateChanges());
1991
                } else {
1992
                    processChanges = false;
1993
                }
1994
 
1995
                if(processChanges && !max_date_changes.isEmpty()) {
1996
                    int new_capsules = data.getInt("new_capsules");
1997
                    String message = new_capsules == 1
1998
                            ? "Hay 1 cápsula nueva disponible"
1999
                            : "Hay " + new_capsules + " cápsulas disponible";
2000
 
2001
 
2002
                    showMessageSnackBarWithClose(message);
2003
 
2004
 
2005
                    preference.setMaxDateChanges(max_date_changes);
2006
 
2007
                    if(!isForeground) {
2008
                        String body = new_capsules == 1
2009
                                ? "Hay 1 cápsula nueva disponible"
2010
                                : "Hay " + new_capsules + " cápsulas disponible";
2011
                        showFcmNotification("Nuevo contenido", body, new_capsules);
2012
                    }
2013
 
2014
                    /*
2015
                    if(!isForeground) {
2016
                        String body = new_capsules == 1
2017
                                ? "Hay 1 cápsula nueva disponible"
2018
                                : "Hay " + new_capsules + " cápsulas disponible";
2019
                        showFcmNotification("Nuevo contenido", body, new_capsules);
2020
 
2021
 
2022
                        AnswerDao answerDao = mAppDatabase.getAnswerDao();
2023
                        answerDao.removeAll();
2024
 
2025
                        QuestionDao questionDao = mAppDatabase.getQuestionDao();
2026
                        questionDao.removeAll();
2027
 
2028
                        QuizDao quizDao = mAppDatabase.getQuizDao();
2029
                        quizDao.removeAll();
2030
 
2031
                        SlideDao slideDao = mAppDatabase.getSlideDao();
2032
                        slideDao.removeAll();
2033
 
2034
                        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
2035
                        capsuleDao.removeAll();
2036
 
2037
                        TopicDao topicDao = mAppDatabase.getTopicDao();
2038
                        topicDao.removeAll();
2039
 
2040
                        CompanyDao companyDao = mAppDatabase.getCompanyDao();
2041
                        companyDao.removeAll();
2042
 
2043
                        UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
2044
                        userExtendedDao.removeAll();
2045
 
2046
 
2047
                        this.syncFromServer(data);
2048
 
2049
 
2050
                        if(!TextUtils.isEmpty(preference.getSlideUuidActive())) {
2051
 
2052
                            Slide slide = mAppDatabase.getSlideDao().selectByUuid(preference.getSlideUuidActive());
2053
                            if(slide == null) {
2054
                                preference.setFragmentIdxActive(Constants.IDX_FRAGMENT_TOPICS);
2055
                                preference.save(this);
2056
                            }
2057
 
2058
                        }
2059
                    }*/
2060
                }
2061
            }
2062
        } catch (JSONException e) {
2063
            Log.d(TAG, e.getMessage());
2064
        }
2065
    }
2066
 
2067
    @Override
2068
    public AppDatabase getDatabase() {
2069
        return mAppDatabase;
2070
    }
2071
 
2072
    @Override
2073
    public void syncToServerOrCheckChanges()
2074
    {
2075
        if(TextUtils.isEmpty(preference.getDeviceUuid())) {
2076
            return;
2077
        }
2078
 
2079
        SyncDao syncDao = mAppDatabase.getSyncDao();
2080
        List<Sync> records = syncDao.selectBatch();
2081
 
2082
        if(records.size() > 0) {
2083
            syncToServer(records);
2084
        } else {
2085
 
2086
                long timeLast = 0;
2087
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2088
                if (!TextUtils.isEmpty(preference.getLastDataRefresh())) {
2089
                    try {
2090
                        timeLast = simpleDateFormat.parse(preference.getLastDataRefresh()).getTime();
2091
                    } catch (Exception e) {
2092
 
2093
                    }
2094
 
2095
                }
2096
 
2097
 
2098
                Calendar calendar = Calendar.getInstance();
2099
                long timeNow = calendar.getTime().getTime();
2100
                 if (timeNow > (timeLast + Constants.CHECK_CHANGES_INTERVAL)) {
2101
                    requestCheckChanges();
2102
                }
2103
        }
2104
    }
2105
 
2106
 
2107
 
2108
    public void syncToServer(List<Sync> records)
2109
    {
2110
 
2111
 
2112
 
2113
        int maxRecordsSyncBatch = 0;
2114
        FormBody.Builder formBodyBatchBuilder = new FormBody.Builder();
2115
        formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_DEVICE_UUID, preference.getDeviceUuid());
2116
 
2117
        for(Sync record : records)
2118
        {
2119
            Log.d(TAG, "SyncRecord ID = " + record.getId() + " Data : "  + record.getData() + " Type= " + record.getType());
2120
 
2121
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {
2122
                Log.d(TAG, "Device");
2123
                isSyncDevice = true;
2124
 
2125
                try {
2126
                    Http http = new Http(this.getCacheDir());
2127
                    OkHttpClient client = http.getHttpClient(false);
2128
 
2129
                    RequestBody formBody = new FormBody.Builder()
2130
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID,  String.valueOf(Configuration.APPLICATION_ID))
2131
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
2132
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
2133
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
2134
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE  + " " + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName())
2135
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
2136
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
2137
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
2138
                            .build();
2139
 
2140
                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
2141
                    Request request = new Request.Builder()
2142
                            .url(Configuration.URL_DEVICE)
2143
                            .post(formBody)
2144
                            .build();
2145
 
2146
                    Call call = client.newCall(request);
2147
                    call.enqueue(new okhttp3.Callback() {
2148
                        public void onResponse(Call call, Response response)
2149
                                throws IOException {
2150
                            isSyncDevice = false;
2151
                            Log.d(TAG, "Response Device :  " +  response.body().toString());
2152
 
2153
                            processResponseSyncToServer(response.body().string());
2154
                        }
2155
 
2156
                        public void onFailure(Call call, IOException e) {
2157
                            isSyncDevice = false;
2158
                            Log.d(TAG, "Error :  " +  e.getMessage());
2159
                        }
2160
                    });
2161
                } catch (Exception e) {
2162
                }
2163
            }
2164
 
2165
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken) {
2166
                isSyncToken = true;
2167
                Log.d(TAG, "FCM");
2168
 
2169
                try {
2170
                    Http http = new Http(this.getCacheDir());
2171
                    OkHttpClient client = http.getHttpClient(false);
2172
 
2173
                    RequestBody formBody = new FormBody.Builder()
2174
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID,preference.getDeviceUuid())
2175
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
2176
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
2177
                            .build();
2178
 
2179
                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
2180
                    Request request = new Request.Builder()
2181
                            .url(Configuration.URL_FCM)
2182
                            .post(formBody)
2183
                            .build();
2184
 
2185
                    Call call = client.newCall(request);
2186
                    call.enqueue(new okhttp3.Callback() {
2187
                        public void onResponse(Call call, Response response)
2188
                                throws IOException {
2189
                            isSyncToken = false;
2190
                            processResponseSyncToServer(response.body().string());
2191
                        }
2192
 
2193
                        public void onFailure(Call call, IOException e) {
2194
                            Log.d(TAG, "Error :  " +  e.getMessage());
2195
                            isSyncToken = false;
2196
                        }
2197
                    });
2198
                } catch (Exception e) {
2199
 
2200
 
2201
                }
2202
            }
2203
 
2204
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_SYNC ) {
2205
                Log.d(TAG, "SYNC BATCH");
2206
                maxRecordsSyncBatch++;
2207
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_DATA + maxRecordsSyncBatch, record.getData());
2208
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_SYNC_ID + maxRecordsSyncBatch, String.valueOf(record.getId()));
2209
            }
2210
        }
2211
 
2212
 
2213
        if(maxRecordsSyncBatch > 0 && !isSyncBatch) {
2214
            Log.d(TAG, "Sync Batch");
2215
            isSyncBatch = true;
2216
 
2217
            try {
2218
                Http http = new Http(this.getCacheDir());
2219
                OkHttpClient client = http.getHttpClient(false);
2220
 
2221
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_MAX_RECORDS, String.valueOf(maxRecordsSyncBatch));
2222
                RequestBody formBody = formBodyBatchBuilder.build();
2223
 
2224
                Log.d(TAG, "URL = " + Configuration.URL_SYNC_BATCH);
2225
                Request request = new Request.Builder()
2226
                    .url(Configuration.URL_SYNC_BATCH)
2227
                    .post(formBody)
2228
                    .build();
2229
 
2230
                Call call = client.newCall(request);
2231
                call.enqueue(new okhttp3.Callback() {
2232
                    public void onResponse(Call call, Response response) throws IOException {
2233
                        isSyncBatch = false;
2234
                        processResponseServerBatch(response.body().string());
2235
                    }
2236
 
2237
                    public void onFailure(Call call, IOException e) {
2238
                        Log.d(TAG, "Error :  " +  e.getMessage());
2239
                        isSyncBatch = false;
2240
                    }
2241
                });
2242
            } catch (Exception e) {
2243
 
2244
 
2245
            }
2246
        }
2247
 
2248
 
2249
    }
2250
 
2251
    private void processResponseServerBatch(String dataString)
2252
    {
2253
        boolean success = false;
2254
        long sync_id = 0;
2255
 
2256
        Log.d(TAG, "processResponseServer = " + dataString);
2257
        try {
2258
            JSONObject objJSON = new JSONObject(dataString);
2259
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2260
            if(success  && objJSON.has("data")) {
2261
                JSONArray jsonArrayData = objJSON.getJSONArray("data");
2262
 
2263
 
2264
                JSONObject jsonObjectData;
2265
                int max = jsonArrayData.length();
2266
                for(int i = 0; i < max; i++) {
2267
                    jsonObjectData = jsonArrayData.getJSONObject(i);
2268
 
2269
                    if(jsonObjectData.has("success") && jsonObjectData.getBoolean("success")) {
2270
                        sync_id = jsonObjectData.getLong("sync_id");
2271
 
2272
                        mAppDatabase.getSyncDao().remove(sync_id);
2273
 
2274
                    }
2275
 
2276
 
2277
                }
2278
 
2279
 
2280
 
2281
                /*
2282
                if(jsonObjectData.has("message")) {
2283
                    message = jsonObjectData.getString("message");
2284
                }
2285
 
2286
                if(jsonObjectData.has("aes")) {
2287
                    preference.setAes(jsonObjectData.getString("aes"));
2288
                    preference.save(this);
2289
                }
2290
 
2291
                if(jsonObjectData.has("password")) {
2292
                    preference.setPassword(jsonObjectData.getString("password"));
2293
                    preference.save(this);
2294
                }
2295
                */
2296
            }
2297
            Log.d(TAG, "SyncID = " + sync_id);
2298
            if(success && sync_id > 0) {
2299
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2300
                mAppDatabase.getSyncDao().remove(sync_id);
2301
            }
2302
        } catch (JSONException e) {
2303
            e.printStackTrace();
2304
        }
2305
    }
2306
 
2307
    private void processResponseSyncToServer(String dataString)
2308
    {
2309
        boolean success = false;
2310
        long sync_id = 0;
2311
 
2312
        Log.d(TAG, "processResponseServer = " + dataString);
2313
        try {
2314
            JSONObject objJSON = new JSONObject(dataString);
2315
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2316
            if(success  && objJSON.has("data")) {
2317
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
2318
 
2319
                if(jsonObjectData.has("sync_id")) {
2320
                    sync_id = jsonObjectData.getLong("sync_id");
2321
                }
2322
 
2323
                /*
2324
                if(jsonObjectData.has("message")) {
2325
                    message = jsonObjectData.getString("message");
2326
                }
2327
 
2328
                if(jsonObjectData.has("aes")) {
2329
                    preference.setAes(jsonObjectData.getString("aes"));
2330
                    preference.save(this);
2331
                }
2332
 
2333
                if(jsonObjectData.has("password")) {
2334
                    preference.setPassword(jsonObjectData.getString("password"));
2335
                    preference.save(this);
2336
                }
2337
                */
2338
            }
2339
            Log.d(TAG, "SyncID = " + sync_id);
2340
            if(success && sync_id > 0) {
2341
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2342
                mAppDatabase.getSyncDao().remove(sync_id);
2343
            }
2344
        } catch (JSONException e) {
2345
            e.printStackTrace();
2346
        }
2347
    }
2348
 
2349
    /*
2350
    private void processResponseServerCheckChanges(String dataString) {
2351
 
2352
        Log.d(TAG, "processResponseServerCheckChanges = " + dataString);
2353
 
2354
        runOnUiThread(new Runnable() {
2355
 
2356
            @Override
2357
            public void run() {
2358
 
2359
                try {
2360
                    JSONObject objJSON = new JSONObject(dataString);
2361
                    boolean success = objJSON.has("success") ? objJSON.getBoolean("success") : false;
2362
                    String message = "";
2363
                    if (objJSON.has("data")) {
2364
                        Object item = objJSON.get("data");
2365
                        if (item instanceof String) {
2366
                            message = item.toString();
2367
                        }
2368
                    }
2369
 
2370
                    if (success) {
2371
                        mAppDatabase.getAnswerDao().removeAll();
2372
                        mAppDatabase.getQuestionDao().removeAll();
2373
                        mAppDatabase.getQuizDao().removeAll();
2374
                        mAppDatabase.getSlideDao().removeAll();
2375
                        mAppDatabase.getCapsuleDao().removeAll();
2376
                        mAppDatabase.getTopicDao().removeAll();
2377
 
2378
 
2379
                        JSONObject data = objJSON.getJSONObject("data");
2380
                        syncFromServer(data);
2381
 
2382
 
2383
                    }
2384
 
2385
 
2386
                } catch (JSONException e) {
2387
                    Log.d(TAG, e.getMessage());
2388
                }
2389
 
2390
                reloadNavHeader();
2391
 
2392
 
2393
            }
2394
        });
2395
    }
2396
     */
2397
 
2398
 
2399
 
2400
}