Proyectos de Subversion Android Microlearning - Inconcert

Rev

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

Rev Autor Línea Nro. Línea
1 gabriel 1
package com.cesams.twogetskills.inconcert.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.AppCompatActivity;
7
import androidx.core.app.NotificationCompat;
8
import androidx.core.content.ContextCompat;
7 gabriel 9
import androidx.core.splashscreen.SplashScreen;
1 gabriel 10
import androidx.fragment.app.Fragment;
11
import androidx.fragment.app.FragmentTransaction;
12
 
13
import android.accounts.Account;
14
import android.accounts.AccountManager;
7 gabriel 15
import android.animation.Animator;
16
import android.animation.AnimatorListenerAdapter;
17
import android.animation.ObjectAnimator;
1 gabriel 18
import android.app.AlertDialog;
19
import android.app.NotificationChannel;
20
import android.app.NotificationManager;
21
import android.app.PendingIntent;
22
import android.content.ContentResolver;
23
import android.content.DialogInterface;
24
import android.net.ConnectivityManager;
25
import android.os.Build;
26
import android.os.Handler;
27
import android.os.Looper;
28
import android.text.TextUtils;
29
import android.util.Log;
30
import android.content.Context;
31
import android.content.Intent;
32
import android.content.IntentFilter;
33
import android.os.Bundle;
34
import android.view.Menu;
35
import android.view.MenuItem;
36
import android.view.View;
7 gabriel 37
import android.view.animation.AnticipateInterpolator;
8 gabriel 38
import android.view.inputmethod.InputMethodManager;
1 gabriel 39
import android.widget.PopupMenu;
40
import android.widget.ProgressBar;
41
import android.widget.TextView;
42
 
43
 
44
import com.cesams.twogetskills.inconcert.Configuration;
45
import com.cesams.twogetskills.inconcert.dao.AnswerDao;
46
import com.cesams.twogetskills.inconcert.dao.AppDatabase;
47
import com.cesams.twogetskills.inconcert.dao.CapsuleDao;
48
import com.cesams.twogetskills.inconcert.dao.CompanyDao;
49
import com.cesams.twogetskills.inconcert.dao.DatabaseHelper;
50
import com.cesams.twogetskills.inconcert.dao.NotificationCenterDao;
51
import com.cesams.twogetskills.inconcert.dao.ProgressDao;
52
import com.cesams.twogetskills.inconcert.dao.QuestionDao;
53
import com.cesams.twogetskills.inconcert.dao.QuizDao;
54
import com.cesams.twogetskills.inconcert.dao.SlideDao;
55
import com.cesams.twogetskills.inconcert.dao.SyncDao;
56
import com.cesams.twogetskills.inconcert.dao.TopicDao;
57
import com.cesams.twogetskills.inconcert.dao.UserExtendedDao;
58
import com.cesams.twogetskills.inconcert.dao.UserLogDao;
59
import com.cesams.twogetskills.inconcert.entity.UserExtended;
8 gabriel 60
import com.cesams.twogetskills.inconcert.fragment.BiometricOptions;
1 gabriel 61
import com.cesams.twogetskills.inconcert.fragment.CapsuleFragment;
62
import com.cesams.twogetskills.inconcert.fragment.CompanyFragment;
63
import com.cesams.twogetskills.inconcert.fragment.FinishCapsuleFragment;
64
import com.cesams.twogetskills.inconcert.fragment.FinishTopicFragment;
65
import com.cesams.twogetskills.inconcert.fragment.GalleryFragment;
66
import com.cesams.twogetskills.inconcert.fragment.NotificationCenter;
67
import com.cesams.twogetskills.inconcert.fragment.ProgressFragment;
68
import com.cesams.twogetskills.inconcert.fragment.SlideFragment;
69
import com.cesams.twogetskills.inconcert.fragment.TimelineFragment;
70
import com.cesams.twogetskills.inconcert.fragment.TopicFragment;
71
import com.cesams.twogetskills.inconcert.fragment.UserProfileFragment;
72
import com.cesams.twogetskills.inconcert.fragment.WelcomeFragment;
73
import com.cesams.twogetskills.inconcert.library.Http;
74
import com.cesams.twogetskills.inconcert.library.MD5;
75
import com.cesams.twogetskills.inconcert.library.UniqueID;
76
import com.cesams.twogetskills.inconcert.entity.Answer;
77
import com.cesams.twogetskills.inconcert.entity.Capsule;
78
import com.cesams.twogetskills.inconcert.entity.Company;
79
import com.cesams.twogetskills.inconcert.entity.Progress;
80
import com.cesams.twogetskills.inconcert.entity.Question;
81
import com.cesams.twogetskills.inconcert.entity.Quiz;
82
import com.cesams.twogetskills.inconcert.entity.Slide;
83
import com.cesams.twogetskills.inconcert.entity.Sync;
84
import com.cesams.twogetskills.inconcert.entity.Topic;
85
import com.cesams.twogetskills.inconcert.entity.UserLog;
86
import com.cesams.twogetskills.inconcert.preference.Preference;
87
import com.cesams.twogetskills.inconcert.receiver.ConnectivityReceiver;
88
import com.cesams.twogetskills.inconcert.receiver.InternalReceiver;
89
import com.cesams.twogetskills.inconcert.room.ResultCount;
90
import com.cesams.twogetskills.inconcert.skeleton.IReloadData;
91
import com.google.android.gms.tasks.OnCompleteListener;
92
import com.google.android.gms.tasks.Task;
93
import com.google.android.material.bottomnavigation.BottomNavigationView;
94
import com.google.android.material.navigation.NavigationBarView;
95
import com.google.android.material.snackbar.Snackbar;
96
 
97
import androidx.appcompat.widget.Toolbar;
98
 
99
import com.cesams.twogetskills.inconcert.Constants;
100
import com.cesams.twogetskills.inconcert.R;
101
 
102
import com.cesams.twogetskills.inconcert.fragment.IntroFragment;
103
import com.cesams.twogetskills.inconcert.fragment.SigninFragment;
104
import com.cesams.twogetskills.inconcert.skeleton.ITwoGetSkills;
105
import com.google.firebase.messaging.FirebaseMessaging;
106
 
7 gabriel 107
 
1 gabriel 108
import org.json.JSONArray;
109
import org.json.JSONException;
110
import org.json.JSONObject;
111
 
112
import java.io.IOException;
113
import java.text.SimpleDateFormat;
114
import java.util.Calendar;
115
import java.util.Date;
116
import java.util.HashMap;
117
import java.util.List;
118
import java.util.Random;
119
import java.util.TimeZone;
120
 
121
//import de.hdodenhof.circleimageview.CircleImageView;
122
import okhttp3.Call;
7 gabriel 123
import okhttp3.Callback;
1 gabriel 124
import okhttp3.FormBody;
125
import okhttp3.OkHttpClient;
126
import okhttp3.Request;
127
import okhttp3.RequestBody;
128
import okhttp3.Response;
129
 
130
public class MainActivity extends  AppCompatActivity implements ITwoGetSkills {
131
    private boolean isSyncDevice = false;
132
    private boolean isSyncToken = false;
133
    private boolean isSyncBatch = false;
134
    private boolean isForeground = false;
135
    private boolean isSmartLockLoginRun = false;
136
    private boolean isShowingCartelRefresh = false;
137
 
138
    private final static String PREFIX_FRAG = "FRAG";
139
    private final static String TAG = "C2GS - MainActivity";
140
 
141
    private HashMap<String, Fragment> fragmentHashMap;
142
    private TextView textViewMessageNotConnection;
143
 
144
    BottomNavigationView mNavigationView;
145
 
146
    private Preference preference;
147
    private boolean connected = false;
148
    private ConnectivityReceiver mConnectivityReceiver;
149
    private InternalReceiver mInternalReceiver;
150
    private ProgressBar mProgressBar;
151
    private Toolbar mToolbar;
152
    private Account mAccount;
153
    private AppDatabase mAppDatabase;
154
 
155
 
156
 
157
    ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(
158
            new ActivityResultContracts.StartActivityForResult(),
159
            result -> {
160
                if(result.getResultCode() == RESULT_OK) {
161
                    boolean completed = result.getData().hasExtra("completed") && result.getData().getBooleanExtra("completed", false);
162
                    int requestCode = result.getData().hasExtra("requestCode") ? result.getData().getIntExtra("requestCode", 0) : 0;
163
                    if(requestCode == Constants.REQUEST_CODE_QUIZ) {
164
                        createProgressAndSyncRecord(preference.getSlideUuidActive(), completed, true, false);
165
                    } else  if(requestCode == Constants.REQUEST_CODE_AUDIO_VIDEO) {
166
                        createProgressAndSyncRecord(preference.getSlideUuidActive(), completed, false, true);
167
                    } else {
168
                        createProgressAndSyncRecord(preference.getSlideUuidActive(), completed, false, false);
169
                    }
170
                }
171
            }
172
    );
173
 
174
 
175
    @Override
176
    protected void onCreate(Bundle savedInstanceState) {
7 gabriel 177
        SplashScreen splashScreen = SplashScreen.installSplashScreen(this);
178
 
179
 
1 gabriel 180
        super.onCreate(savedInstanceState);
181
        setContentView(R.layout.activity_main);
182
 
7 gabriel 183
            Log.d(TAG, "MainActivity onCreate");
1 gabriel 184
 
7 gabriel 185
            mAppDatabase = DatabaseHelper.getInstance(getApplicationContext()).getAppDatabase();
1 gabriel 186
 
7 gabriel 187
            preference = Preference.getInstance(getApplicationContext());
1 gabriel 188
 
7 gabriel 189
            preference.load();
1 gabriel 190
 
7 gabriel 191
            if(TextUtils.isEmpty(preference.getDeviceUuid())) {
192
                Log.e("BUG Token", "Preference - Set Device");
193
                String uuid = UniqueID.id(getApplicationContext());
194
                preference.setDeviceUuid(uuid);
195
                preference.save();
1 gabriel 196
 
7 gabriel 197
                Log.e("BUG Token", "SyncRecord - Device");
198
                Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_DEVICE, uuid);
199
                mAppDatabase.getSyncDao().insert(sync);
1 gabriel 200
 
7 gabriel 201
                if (!TextUtils.isEmpty(preference.getDeviceToken())) {
202
                    Log.e("BUG Token", "SyncRecord - FCM1");
203
                    sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, preference.getDeviceToken());
204
                    mAppDatabase.getSyncDao().insert(sync);
205
                }
1 gabriel 206
            }
207
 
7 gabriel 208
            /**** CANAL DE NOTIFICACIONES **/
209
            createNotificationChannel();
210
           // badgenotification= findViewById(R.id.cart_badge);
1 gabriel 211
 
212
 
7 gabriel 213
            /*** CUENTAS DE SINCRONIZACION **/
214
            mAccount =  CreateSyncAccount(getApplicationContext());
1 gabriel 215
 
7 gabriel 216
            textViewMessageNotConnection = findViewById(R.id.main_activity_text_view_message_not_connection);
1 gabriel 217
 
218
 
7 gabriel 219
            mConnectivityReceiver = new ConnectivityReceiver();
220
            registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
1 gabriel 221
 
7 gabriel 222
            IntentFilter intentFilterInternal = new IntentFilter();
223
            intentFilterInternal.addAction(Constants.BROADCAST_TYPE_NOTIFICATION);
224
            intentFilterInternal.addAction(Constants.BROADCAST_TYPE_TOKEN);
225
            intentFilterInternal.addAction(Constants.BROADCAST_TYPE_COMMAND);
226
            intentFilterInternal.addAction(Constants.BROADCAST_TYPE_SYNC_TO_SERVER_OR_CHECK_CHANGES);
1 gabriel 227
 
7 gabriel 228
            mInternalReceiver = new InternalReceiver();
229
            this.registerReceiver(mInternalReceiver, intentFilterInternal);
1 gabriel 230
 
231
 
7 gabriel 232
            fragmentHashMap = new HashMap<>();
1 gabriel 233
 
7 gabriel 234
            mProgressBar = findViewById(R.id.progressBar);
235
            mToolbar = findViewById(R.id.toolbar);
236
            mToolbar.setOverflowIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.toolbarnotifi));
237
            setSupportActionBar(findViewById(R.id.toolbar));
238
            getSupportActionBar().setIcon(R.drawable.inconcertmargin);
1 gabriel 239
 
7 gabriel 240
            mNavigationView = findViewById(R.id.bottomNavigationView);
1 gabriel 241
 
7 gabriel 242
            mNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
243
                @Override
244
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
1 gabriel 245
 
8 gabriel 246
                    //Ocultamos el teclado para mejor experiencia
247
                    hideKeyboard(mNavigationView);
1 gabriel 248
 
7 gabriel 249
                  if(item.getItemId()==R.id.action_home){
1 gabriel 250
 
7 gabriel 251
                      setTitleActionBar(getString(R.string.app_name));
252
                      invokeFragment(Constants.IDX_FRAGMENT_WELCOME);
253
                      mNavigationView.getMenu().getItem(0).setChecked(true);
1 gabriel 254
 
255
 
7 gabriel 256
                  }
1 gabriel 257
 
7 gabriel 258
                    if(item.getItemId()==R.id.action_topicos){
1 gabriel 259
 
7 gabriel 260
                        setTitleActionBar(getString(R.string.menu_topics));
261
                        preference.setOrigennavigation("");
262
                        invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
263
                        mNavigationView.getMenu().getItem(1).setChecked(true);
1 gabriel 264
 
7 gabriel 265
                    }
1 gabriel 266
 
7 gabriel 267
                    if(item.getItemId()==R.id.action_progreso){
1 gabriel 268
 
7 gabriel 269
                        setTitleActionBar(getString(R.string.progress_title));
270
                        invokeFragment(Constants.IDX_FRAGMENT_COMPANIES);
271
                        mNavigationView.getMenu().getItem(2).setChecked(true);
1 gabriel 272
 
7 gabriel 273
                    }
1 gabriel 274
 
7 gabriel 275
                    if(item.getItemId()==R.id.action_more){
1 gabriel 276
 
7 gabriel 277
                        PopupMenu popupMenu = new PopupMenu(MainActivity.this,MainActivity.this.findViewById(R.id.action_more));
1 gabriel 278
 
7 gabriel 279
                        // Inflating popup menu from popup_menu.xml file
280
                        popupMenu.getMenuInflater().inflate(R.menu.more_menu, popupMenu.getMenu());
281
                        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
282
                            @Override
283
                            public boolean onMenuItemClick(MenuItem menuItem) {
284
                                // Toast message on menu item clicked
285
                                //Toast.makeText(MainActivity.this, "You Clicked " + menuItem.getTitle(), Toast.LENGTH_SHORT).show();
286
                                if(menuItem.getItemId()==R.id.miperfil){
287
                                     setTitleActionBar(getString(R.string.menu_user_profile));
288
                                     invokeFragment(Constants.IDX_FRAGMENT_USER_PROFILE);
289
                                }
290
                                if(menuItem.getItemId()==R.id.lineadeltiempo){
291
                                    setTitleActionBar(getString(R.string.menu_timeline));
292
                                    invokeFragment(Constants.IDX_FRAGMENT_TIMELINE);
293
                                }
294
 
295
                                return true;
1 gabriel 296
                            }
7 gabriel 297
                        });
298
                        // Showing the popup menu
299
                        popupMenu.show();
1 gabriel 300
 
7 gabriel 301
                        mNavigationView.getMenu().getItem(3).setChecked(true);
1 gabriel 302
 
7 gabriel 303
                    }
1 gabriel 304
 
7 gabriel 305
 
306
                    return false;
1 gabriel 307
                }
7 gabriel 308
            });
1 gabriel 309
 
310
 
311
 
7 gabriel 312
        FirebaseMessaging.getInstance().getToken()
313
                .addOnCompleteListener(new OnCompleteListener<String>() {
314
                    @Override
315
                    public void onComplete(@NonNull Task<String> task) {
316
                        if (!task.isSuccessful()) {
317
                            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
318
                            return;
319
                        }
1 gabriel 320
 
7 gabriel 321
                        // Get new FCM registration token
322
                        String token = task.getResult();
1 gabriel 323
 
324
 
7 gabriel 325
                        if(preference.getDeviceToken().isEmpty() || !preference.getDeviceToken().equals(token)) {
326
                            createSyncRecordNewToken(token);
327
                            Log.e("BUG Token", "Token 1 :  " + token);
1 gabriel 328
 
7 gabriel 329
                        }
330
                    }
331
                });
1 gabriel 332
 
333
 
7 gabriel 334
            final Handler handler = new Handler(Looper.getMainLooper());
335
            handler.postDelayed(new Runnable() {
336
                @Override
337
                public void run() {
338
                    FirebaseMessaging.getInstance().setAutoInitEnabled(true);
1 gabriel 339
                }
7 gabriel 340
            }, 10000);
1 gabriel 341
 
7 gabriel 342
            if (getIntent().getExtras() != null) {
1 gabriel 343
 
7 gabriel 344
                for (String key : getIntent().getExtras().keySet()) {
345
                    Object value = getIntent().getExtras().get(key);
346
                    if(value.toString().equals("content-refresh") && !isShowingCartelRefresh)
347
                        {
1 gabriel 348
 
7 gabriel 349
                            Log.e("OnCreate","intent cartel");
1 gabriel 350
 
7 gabriel 351
                            //Vengo de notificacion, pero el app estaba cerrada, asi que muestro el cartel de content-refresh
352
                           // preference.setRefreshContentRequired(true);
353
                            saveNotificationCenterNew("Nuevo contenido para descargar","","Tienes nuevas capsulas de aprendizaje para descargar");
354
                            CartelRefreshContent();
1 gabriel 355
 
7 gabriel 356
                        }
1 gabriel 357
 
7 gabriel 358
                }
1 gabriel 359
 
360
 
361
            }
362
    }
363
 
8 gabriel 364
    public void hideKeyboard(View view) {
365
 
366
        try {
367
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
368
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
369
        } catch (Exception e) {
370
            e.printStackTrace();
371
        }
372
    }
373
 
1 gabriel 374
    @Override
375
    protected void onDestroy() {
376
        super.onDestroy();
377
 
378
        try  {
379
            unregisterReceiver(mConnectivityReceiver);
380
            unregisterReceiver(mInternalReceiver);
381
        } catch (IllegalArgumentException e) {
382
            e.printStackTrace();
383
        }
384
    }
385
 
386
    @Override
387
    public boolean onOptionsItemSelected(MenuItem item) {
388
        if (item.getItemId()==R.id.action_notifications) {// Toast.makeText(this, "Abriendo centro de notificaciones", Toast.LENGTH_LONG).show();
389
            invokeFragment(Constants.IDX_FRAGMENT_NOTIFICATION);
8 gabriel 390
            //Ocultamos el teclado para mejor experiencia
391
            hideKeyboard(mNavigationView);
1 gabriel 392
        }
393
        return true;
394
    }
395
 
396
    @Override
397
    protected void onResume() {
398
        super.onResume();
399
        isForeground = true;
400
 
401
        preference = Preference.getInstance(getApplicationContext());
402
        preference.load();
403
 
404
        if(preference.isRefreshContentRequired() && !isShowingCartelRefresh)
405
        {
406
            //Hubo una notificacion de actualización de contenido antes
407
            // pero no se pudo procesar por alguna interrupcion
408
            CartelRefreshContent();
409
        }
410
 
411
        if(TextUtils.isEmpty(preference.getUserUuid())) {
412
 
413
            //Verifico que el teclado no vaya a relanzar el fragment de intro al usar Google Smartlock para traer
414
            //Informacion de inicio de sesion almacenada en su cuenta personal de Google
415
            if (!isSmartLockLoginRun) {
416
                invokeFragment(Constants.IDX_FRAGMENT_INTRO);
417
                isSmartLockLoginRun= true;
418
            }
419
 
420
 
421
        } else {
422
            if(preference.getFragmentIdxActive() == 0) {
8 gabriel 423
                if(preference.getBiometricLogin())
424
                {
425
                    hideNavigationAndtoolbar();
426
                    invokeFragment(Constants.IDX_FRAGMENT_BIOMETRIC);
427
                }
428
                else{
1 gabriel 429
                invokeFragment(Constants.IDX_FRAGMENT_WELCOME); //La pantalla principal ahora es Welcome, no Topic
8 gabriel 430
                }
431
 
1 gabriel 432
            } else {
8 gabriel 433
                if(preference.getBiometricLogin())
434
                {
435
                    hideNavigationAndtoolbar();
436
                    invokeFragment(Constants.IDX_FRAGMENT_BIOMETRIC);
437
                }else
438
                {
1 gabriel 439
                invokeFragment(preference.getFragmentIdxActive());
440
            }
8 gabriel 441
            }
1 gabriel 442
        }
443
 
444
    }
445
 
446
    @Override
447
    protected void onPause() {
448
        super.onPause();
449
 
450
        isForeground = false;
451
        preference.save();
452
    }
453
 
454
 
455
    private void createNotificationChannel() {
456
        // Create the NotificationChannel, but only on API 26+ because
457
        // the NotificationChannel class is new and not in the support library
458
        CharSequence name = getString(R.string.channel_name);
459
        String description = getString(R.string.channel_description);
460
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
461
        NotificationChannel channel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, name, importance);
462
        channel.setDescription(description);
463
        channel.setShowBadge(true);
464
 
465
 
466
        // Register the channel with the system; you can't change the importance
467
        // or other notification behaviors after this
468
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
469
        notificationManager.createNotificationChannel(channel);
470
    }
471
 
472
 
473
    @Override
474
    public void showFcmNotification(String title, String body, int new_capsules, String url, Boolean content_refresh)
475
    {
476
 
477
        NotificationCompat.Builder builder =
478
                new NotificationCompat.Builder(MainActivity.this, Constants.NOTIFICATION_CHANNEL_ID)
479
                        .setSmallIcon(R.drawable.ic_notificacion) //set icon for notification
480
                        .setContentTitle(title) //set title of notification
481
                        .setContentText(body)//this is notification message
482
                        .setAutoCancel(true) // makes auto cancel of notification
483
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of notification
484
 
485
        if(new_capsules > 0) {
486
            builder.setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE);
487
            builder.setNumber(new_capsules);
488
        }
489
 
490
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
491
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
492
        //notification message will get at NotificationView
493
        notificationIntent.putExtra(title, body);
494
 
495
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
496
                PendingIntent.FLAG_IMMUTABLE);
497
        builder.setContentIntent(pendingIntent);
498
 
499
        // Add as notification
500
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
501
        manager.notify(0, builder.build());
502
 
503
 
504
 
505
 
506
        if(new_capsules > 0) {
507
 
508
            String message = new_capsules == 1
509
                    ? "Hay 1 cápsula nueva disponible"
510
                    : "Hay " + new_capsules + " cápsulas disponible";
511
 
512
 
513
            showMessageSnackBarWithClose(message);
514
 
515
            saveNotificationCenterNew("Nueva cápsula","",message);
516
        } else {
517
 
518
            showMessageSnackBarWithClose(body);
519
            saveNotificationCenterNew(title,"",body);
520
 
521
        }
522
 
523
    if(content_refresh)
524
    {
525
        if(!isShowingCartelRefresh)
526
        {
527
            Log.e("On fcm mensaje boolean","intent cartel");
528
 
529
 
530
            CartelRefreshContent();
531
        }
532
    }
533
 
534
 
535
    }
536
 
537
    public void saveNotificationCenterNew(String title,String url,String message){
538
 
539
        Calendar calendar = Calendar.getInstance();
540
        Date date = calendar.getTime();
7 gabriel 541
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATE_SERVICE);
1 gabriel 542
        String  dateOn = simpleDateFormat.format(date);
543
 
544
        NotificationCenterDao notificacionDao =  mAppDatabase.getNotificationCenterDao();
545
        com.cesams.twogetskills.inconcert.entity.NotificationCenter notificacionueva;
546
 
547
        notificacionueva = new com.cesams.twogetskills.inconcert.entity.NotificationCenter();
548
 
549
 
550
        notificacionueva.setTitle(title);
551
        notificacionueva.setDate(dateOn);
552
        notificacionueva.setUrl(url);
553
 
554
        List<com.cesams.twogetskills.inconcert.entity.NotificationCenter> lista;
555
        lista=notificacionDao.selectAllNotification();
556
 
557
        boolean registrada=false;
558
        notificacionueva.setDescription(message);
559
 
560
        for(com.cesams.twogetskills.inconcert.entity.NotificationCenter notificacion: lista)
561
        {
562
            if(notificacion.getDescription().equals(notificacionueva.getDescription()))
563
            {
564
                registrada=true;
565
                //Ya existia, como llego de nuevo la pongo en no vista nuevamente.
566
                notificacionueva.setId(notificacion.getId());
567
                notificacionueva.setViewed("No");
568
                notificacionDao.update(notificacionueva);
569
                Log.e("Ya existia","la notificacion: "+notificacion.getDescription());
570
            }
571
 
572
        }
573
        if(!registrada)
574
        {
575
            notificacionDao.insert(notificacionueva);
576
 
7 gabriel 577
            // region - Datos de prueba
578
            /*
579
            notificacionueva.setTitle("Otra cosa");
580
            notificacionueva.setDate("2022-07-19");
581
            notificacionueva.setDescription("Esto es prueba");
582
            notificacionDao.insert(notificacionueva);
583
 
584
            notificacionueva.setTitle("Alguna cosa");
585
            notificacionueva.setDate("2022-07-05");
586
            notificacionueva.setDescription("Otro nitificacion");
587
            notificacionDao.insert(notificacionueva);
588
 
589
            notificacionueva.setTitle("Alguna cosa");
590
            notificacionueva.setDate("2022-07-05");
591
            notificacionueva.setDescription("Otro de ese dia");
592
            notificacionDao.insert(notificacionueva);
593
*/
594
            // endregion
595
 
1 gabriel 596
        }
597
 
598
    }
599
 
600
    @Override
601
    public void saveNotificationCenter(String title, String url, String mensaje) {
602
        saveNotificationCenterNew(title,url,mensaje);
603
    }
604
 
605
    @Override
606
    public void signout()
607
    {
608
        mAppDatabase.getAnswerDao().removeAll();
609
        mAppDatabase.getQuestionDao().removeAll();
610
        mAppDatabase.getQuizDao().removeAll();
611
        mAppDatabase.getSlideDao().removeAll();
612
        mAppDatabase.getCapsuleDao().removeAll();
613
        mAppDatabase.getTopicDao().removeAll();
614
        mAppDatabase.getUserExtendedDao().removeAll();
615
 
616
 
617
        mAppDatabase.getUserLogDao().removeAll();
618
        mAppDatabase.getProgressDao().removeAll();
619
        mAppDatabase.getNotificationCenterDao().removeAllnotifications();
620
 
621
        preference.setUserUuid("");
622
        preference.setFirstName("");
623
        preference.setLastName("");
624
        preference.setEmail("");
625
        preference.setImage("");
626
        preference.setMaxDateChanges("");
627
        preference.setCompanyCount(0);
628
        preference.setCompanyUuidActive("");
629
        preference.setTopicUuidActive("");
630
        preference.setCapsuleUuidActive("");
631
        preference.setSlideUuidActive("");
632
        preference.save();
633
 
634
        hideNavigationAndtoolbar();
635
 
636
        invokeFragment(Constants.IDX_FRAGMENT_INTRO);
637
    }
638
 
639
    @Override
640
    public void onBackPressed() {
641
 
642
       // Log.e("Origen navegacion",""+preference.getOrigenNavigation());
643
 
644
        //super.onBackPressed();
645
        switch (preference.getFragmentIdxActive())
646
        {
647
 
648
/*
649
            case Constants.IDX_FRAGMENT_INTRO :
650
            case Constants.IDX_FRAGMENT_SIGNIN  :
651
            case Constants.IDX_FRAGMENT_TOPICS  :
652
                finish();
653
                return;*/
654
 
655
            case Constants.IDX_FRAGMENT_PROGRESS :
656
               if(preference.getCompanyCount() > 1) {
657
                   invokeFragment(Constants.IDX_FRAGMENT_COMPANIES);
658
               } else {
659
                   invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
660
               }
661
               break;
662
 
663
            case Constants.IDX_FRAGMENT_COMPANIES:
664
            case Constants.IDX_FRAGMENT_TIMELINE  :
665
                break;
666
            case Constants.IDX_FRAGMENT_CAPSULES :
667
 
668
                if(preference.getOrigenNavigation().equals(""))
669
                {
670
                    preference.setOrigennavigation("");
671
                    setTitleActionBar(getString(R.string.app_name));
672
                    invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
673
 
674
                }
675
                else {
676
                    invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
677
                }
678
 
679
                break;
680
            case Constants.IDX_FRAGMENT_FINISH_TOPIC :
681
 
682
                preference.setTopicUuidActive("");
683
                preference.setCapsuleUuidActive("");
684
                preference.setSlideUuidActive("");
685
                preference.save();
686
 
687
                invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
688
                return;
689
 
690
            case Constants.IDX_FRAGMENT_SLIDES :
691
 
692
                if(preference.getOrigenNavigation().equals("welcome"))
693
                {
694
                    preference.setOrigennavigation("");
695
                    setTitleActionBar(getString(R.string.app_name));
696
                    invokeFragment(Constants.IDX_FRAGMENT_WELCOME);
697
 
698
                }
699
                else {
700
                    invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
701
                }
702
 
703
 
704
 
705
                return;
706
 
707
            case Constants.IDX_FRAGMENT_GALLERY :
708
 
709
                if(preference.getOrigenNavigation().equals("welcome"))
710
                {
711
                    preference.setOrigennavigation("");
712
                    setTitleActionBar(getString(R.string.app_name));
713
                    invokeFragment(Constants.IDX_FRAGMENT_WELCOME);
714
 
715
                }
716
                else {
717
                    invokeFragment(Constants.IDX_FRAGMENT_SLIDES);
718
                }
719
                return;
720
 
721
            case Constants.IDX_FRAGMENT_FINISH_CAPSULE :
722
                preference.setCapsuleUuidActive("");
723
                preference.setSlideUuidActive("");
724
                preference.save();
725
 
726
                invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
727
                return;
728
 
729
        }
730
    }
731
 
732
 
733
 
734
    @Override
735
    public void hideProgressBar() {
736
 
737
        //accessing it from ui-thread
738
        runOnUiThread(new Runnable() {
739
            @Override
740
            public void run() {
741
                mProgressBar.setVisibility(View.INVISIBLE);
742
            }
743
        });
744
 
745
    }
746
 
747
    @Override
748
    public void showProgressBar() {
749
        runOnUiThread(new Runnable() {
750
            @Override
751
            public void run() {
752
                mProgressBar.setVisibility(View.VISIBLE);
753
            }
754
        });
755
 
756
 
757
    }
758
 
759
    @Override
760
    public void hideNavigationAndtoolbar() {
761
 
762
       // Log.e("Ocultar"," Navigation and Toolbar");
763
        //accessing it from ui-thread
764
        runOnUiThread(() -> {
765
            mNavigationView.setVisibility(View.GONE);
766
            mToolbar.setVisibility(View.GONE);
767
        });
768
 
769
    }
770
 
771
    @Override
772
    public void showNavigationAndToolbar() {
773
        runOnUiThread(new Runnable() {
774
            @Override
775
            public void run() {
776
                mNavigationView.setVisibility(View.VISIBLE);
777
                mToolbar.setVisibility(View.VISIBLE);
778
            }
779
        });
780
 
781
 
782
    }
783
 
784
 
785
 
786
    @Override
787
    public boolean onCreateOptionsMenu(Menu menu) {
788
        // Inflate the menu; this adds items to the action bar if it is present.
789
        getMenuInflater().inflate(R.menu.drawer, menu);
790
        return true;
791
    }
792
 
793
 
794
      /**
795
         * Create a new dummy account for the sync adapter
796
         *
797
         * @param context The application context
798
         */
799
    public static Account CreateSyncAccount(Context context) {
800
        // Create the account type and default account
801
        Account newAccount = new Account(
802
                Constants.ACCOUNT, Constants.ACCOUNT_TYPE);
803
        // Get an instance of the Android account manager
804
        AccountManager accountManager =
805
                (AccountManager) context.getSystemService(
806
                        ACCOUNT_SERVICE);
807
        /*
808
         * Add the account and account type, no password or user data
809
         * If successful, return the Account object, otherwise report an error.
810
         */
811
        if (accountManager.addAccountExplicitly(newAccount, null, null)) {
812
            /*
813
             * If you don't set android:syncable="true" in
814
             * in your <provider> element in the manifest,
815
             * then call context.setIsSyncable(account, AUTHORITY, 1)
816
             * here.
817
             */
818
 
819
            ContentResolver.setIsSyncable(newAccount, Constants.AUTHORITY, 1);
820
            ContentResolver.setSyncAutomatically(newAccount, Constants.AUTHORITY, true);
821
            ContentResolver.addPeriodicSync(newAccount,
822
                    Constants.AUTHORITY,  Bundle.EMPTY, Constants.SYNC_INTERVAL);
823
 
824
 
825
        } else {
826
            /*
827
             * The account exists or some other error occurred. Log this, report it,
828
             * or handle it internally.
829
             */
830
 
831
            Account[] accounts = accountManager.getAccounts();
832
            if(accounts != null && accounts.length > 0) {
833
 
834
                for(Account account : accounts)
835
                {
836
                    if(account.type.equals(Constants.ACCOUNT_TYPE)) {
837
                        return account;
838
                    }
839
                }
840
                return accounts[0];
841
            } else {
842
                return null;
843
            }
844
 
845
 
846
 
847
        }
848
 
849
        return newAccount;
850
 
851
 
852
    }
853
 
854
 
855
 
856
 
857
 
858
    @Override
859
    public void createSyncRecordNewToken(String token)
860
    {
861
 
862
        Log.e("BUG Token", "Preference - Set Token");
863
      //Prueba de regeneracion de token
864
         preference.setDeviceToken (token);
865
         preference.save();
866
 
867
        if(!TextUtils.isEmpty(preference.getDeviceUuid())) {
868
            Log.e("BUG Token", "SyncRecord - FCM1");
869
            Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, token);
870
            mAppDatabase.getSyncDao().insert(sync);
871
        }
872
    }
873
 
874
 
875
 
876
 
877
    @Override
878
    public void executeFcmCommand(String command)
879
    {
880
 
881
        if (command.equals("signout")) {
882
            signout();
883
        }
884
 
885
 
886
        if (command.equals("content-refresh")){
887
 
888
            if (!isShowingCartelRefresh) {
889
 
890
                Log.e("On Execute fcm command","intent cartel");
891
 
892
                saveNotificationCenterNew("Nuevo contenido para descargar", "", "Tienes nuevas capsulas de aprendizaje para descargar");
893
 
894
               // preference.setRefreshContentRequired(true);
895
 
896
                CartelRefreshContent();
897
 
898
            }
899
        }
900
 
901
 
902
    }
903
 
904
    public void CartelRefreshContent (){
905
 
906
        isShowingCartelRefresh= true;
907
 
908
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
909
        alertDialogBuilder.setMessage("Tienes nuevas capsulas para descargar");
910
        alertDialogBuilder.setPositiveButton("Si, actualizar ahora",
911
                new DialogInterface.OnClickListener() {
912
                    @Override
913
                    public void onClick(DialogInterface arg0, int arg1) {
914
 
915
                        preference.setRefreshContentRequired(true);
916
 
917
                        if(preference.getFragmentIdxActive() == Constants.IDX_FRAGMENT_TOPICS) {
918
 
919
                            String fragmentKeyActual = PREFIX_FRAG + preference.getFragmentIdxActive();
920
                            if (fragmentHashMap.containsKey(fragmentKeyActual)) {
921
                                Fragment fragment = fragmentHashMap.get(fragmentKeyActual);
922
                                if (fragment instanceof IReloadData) {
923
                                    ((IReloadData) fragment).onReloadData();
924
                                }
925
                            }
926
                        }
927
                        else{
928
                            invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
929
 
930
                        }
931
                    }
932
                });
933
 
934
 
935
        AlertDialog alertDialog = alertDialogBuilder.create();
936
        alertDialog.show();
937
        alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.teal_700, null));
938
        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
939
            @Override
940
            public void onDismiss(DialogInterface dialogInterface) {
941
                isShowingCartelRefresh=false;
942
            }
943
        });
944
 
945
    }
946
 
947
    @Override
948
    protected void onNewIntent(Intent intent) {
949
        super.onNewIntent(intent);
950
 
951
        if(intent.getExtras() != null) {
952
            for (String key : intent.getExtras().keySet()) {
953
                Object value = intent.getExtras().get(key);
954
                if (value.toString().equals("content-refresh")) {
955
                    if (!isShowingCartelRefresh) {
956
                      //  preference.setRefreshContentRequired(true);
957
                        saveNotificationCenterNew("Nuevo contenido para descargar", "", "Tienes nuevas capsulas de aprendizaje para descargar");
958
 
959
                        Log.e("On new","intent cartel");
960
                        CartelRefreshContent();
961
                    }
962
                }
963
            }
964
        }
965
    }
966
 
967
    @Override
968
    public void setConnectedInternet(Boolean isConnected)
969
    {
970
        connected = isConnected;
971
        textViewMessageNotConnection.setVisibility(isConnected ? View.INVISIBLE : View.VISIBLE);
972
    }
973
 
974
    @Override
975
    public boolean isConnectedInternet() {
976
        return connected;
977
    }
978
 
979
    @Override
980
    public void showMessageSnackBar(String message) {
981
        Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_LONG).show();
982
    }
983
 
984
 
985
    @Override
986
    public void showMessageSnackBarWithClose(String message) {
987
 
988
        final Snackbar snackBar = Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_INDEFINITE);
989
 
990
        snackBar.setAction(R.string.snackbar_close, new View.OnClickListener() {
991
            @Override
992
            public void onClick(View v) {
993
                // Call your action method here
994
                snackBar.dismiss();
995
            }
996
        });
997
       snackBar.show();
998
 
999
 
1000
    }
1001
 
1002
    @Override
1003
    public void onErrorFatal() {
1004
 
1005
 
1006
        invokeFragment(Constants.IDX_FRAGMENT_SIGNIN);
1007
    }
1008
 
1009
    @Override
1010
    public void invokeFragment(int fragmentIdxActiveNuevo)
1011
    {
1012
       // Log.e("Invoco fragmento"," "+fragmentIdxActiveNuevo);
1013
 
1014
        String fragmentKeyActual    = PREFIX_FRAG + preference.getFragmentIdxActive();
1015
        String fragmentKeyNuevo 	= PREFIX_FRAG + fragmentIdxActiveNuevo;
1016
        preference.setFragmentIdxActive(fragmentIdxActiveNuevo);
1017
        preference.save();
1018
 
1019
        Fragment fragment;
1020
        if(!fragmentKeyActual.equalsIgnoreCase(fragmentKeyNuevo)) {
1021
            if(fragmentHashMap.containsKey(fragmentKeyActual)) {
1022
                fragment = fragmentHashMap.get(fragmentKeyActual);
1023
                if(fragment != null) {
1024
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
1025
                    fragmentTransaction.hide(fragment);
1026
                    fragmentTransaction.commitAllowingStateLoss();
1027
                }
1028
            }
1029
        }
1030
 
1031
        boolean add = false;
1032
        fragment = null;
1033
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
1034
      //  mDrawerToggle.setDrawerIndicatorEnabled(false);
1035
 
1036
 
1037
        switch(fragmentIdxActiveNuevo) {
1038
            case Constants.IDX_FRAGMENT_SIGNIN :
1039
               // badgenotification.setVisibility(View.GONE);
1040
 
1041
                // getSupportActionBar().hide();
1042
                 if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1043
                     fragment = fragmentHashMap.get(fragmentKeyNuevo);
1044
                 } else {
1045
                     add = true;
1046
                     fragment = new SigninFragment();
1047
                 }
1048
                break;
1049
 
8 gabriel 1050
            case Constants.IDX_FRAGMENT_BIOMETRIC:
1051
                // badgenotification.setVisibility(View.GONE);
1052
 
1053
                // getSupportActionBar().hide();
1054
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1055
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1056
                } else {
1057
                    add = true;
1058
                    fragment = new BiometricOptions();
1059
                }
1060
                break;
1061
 
1 gabriel 1062
            case Constants.IDX_FRAGMENT_TOPICS :
1063
              //  badgenotification.setVisibility(View.GONE);
1064
 
1065
               // getSupportActionBar().show();
1066
             //   mDrawerToggle.setDrawerIndicatorEnabled(true);
1067
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1068
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1069
                } else {
1070
                    add = true;
1071
                    fragment = new TopicFragment();
1072
                }
1073
                break;
1074
 
1075
            case Constants.IDX_FRAGMENT_NOTIFICATION:
1076
               // badgenotification.setVisibility(View.VISIBLE);
1077
 
1078
                // getSupportActionBar().show();
1079
                //   mDrawerToggle.setDrawerIndicatorEnabled(true);
1080
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1081
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1082
                } else {
1083
                    add = true;
1084
                    fragment = new NotificationCenter();
1085
                }
1086
                break;
1087
 
1088
 
1089
            case Constants.IDX_FRAGMENT_CAPSULES :
1090
              //  badgenotification.setVisibility(View.GONE);
1091
 
1092
                //  getSupportActionBar().show();
1093
              //  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1094
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1095
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1096
                } else {
1097
                    add = true;
1098
                    fragment = new CapsuleFragment();
1099
                }
1100
                break;
1101
 
1102
            case Constants.IDX_FRAGMENT_SLIDES :
1103
               // badgenotification.setVisibility(View.GONE);
1104
 
1105
                //   getSupportActionBar().show();
1106
             //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1107
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1108
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1109
                } else {
1110
                    add = true;
1111
                    fragment = new SlideFragment();
1112
                }
1113
                break;
1114
 
1115
            case Constants.IDX_FRAGMENT_GALLERY :
1116
               // badgenotification.setVisibility(View.GONE);
1117
 
1118
                //   getSupportActionBar().show();
1119
             //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1120
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1121
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1122
                } else {
1123
                    add = true;
1124
                    fragment = new GalleryFragment();
1125
                }
1126
 
1127
                break;
1128
 
1129
            case Constants.IDX_FRAGMENT_FINISH_CAPSULE :
1130
               // badgenotification.setVisibility(View.GONE);
1131
 
1132
                //  getSupportActionBar().hide();
1133
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1134
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1135
                } else {
1136
                    add = true;
1137
                    fragment = new FinishCapsuleFragment();
1138
                }
1139
                break;
1140
 
1141
            case Constants.IDX_FRAGMENT_FINISH_TOPIC :
1142
               // badgenotification.setVisibility(View.GONE);
1143
 
1144
                //  getSupportActionBar().hide();
1145
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1146
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1147
                } else {
1148
                    add = true;
1149
                    fragment = new FinishTopicFragment();
1150
                }
1151
                break;
1152
 
1153
            case Constants.IDX_FRAGMENT_TIMELINE :
1154
               // badgenotification.setVisibility(View.GONE);
1155
 
1156
                //  getSupportActionBar().show();
1157
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1158
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1159
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1160
                } else {
1161
                    add = true;
1162
                    fragment = new TimelineFragment();
1163
                }
1164
                break;
1165
 
1166
            case Constants.IDX_FRAGMENT_COMPANIES:
1167
               // badgenotification.setVisibility(View.GONE);
1168
 
1169
                //  getSupportActionBar().show();
1170
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1171
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1172
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1173
                } else {
1174
                    add = true;
1175
                    fragment = new CompanyFragment();
1176
                }
1177
                break;
1178
 
1179
            case Constants.IDX_FRAGMENT_PROGRESS :
1180
               // badgenotification.setVisibility(View.GONE);
1181
 
1182
                // getSupportActionBar().show();
1183
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1184
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1185
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1186
                } else {
1187
                    add = true;
1188
                    fragment = new ProgressFragment();
1189
                }
1190
                break;
1191
 
1192
            case Constants.IDX_FRAGMENT_USER_PROFILE:
1193
               // badgenotification.setVisibility(View.GONE);
1194
 
1195
                // getSupportActionBar().show();
1196
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1197
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1198
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1199
                } else {
1200
                    add = true;
1201
                    fragment = new UserProfileFragment();
1202
                }
1203
                break;
1204
 
1205
            case Constants.IDX_FRAGMENT_WELCOME:
1206
               // badgenotification.setVisibility(View.VISIBLE);
1207
                // getSupportActionBar().show();
1208
                //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1209
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1210
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1211
                } else {
1212
                    add = true;
1213
                    fragment = new WelcomeFragment();
1214
                  //  Log.e("Vete"," a welcome");
1215
                }
1216
                break;
1217
 
1218
            default :
1219
               // getSupportActionBar().hide();
1220
               // badgenotification.setVisibility(View.GONE);
1221
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1222
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1223
                } else {
1224
                    add = true;
1225
                    fragment = new IntroFragment();
1226
                }
1227
                break;
1228
 
1229
 
1230
        }
1231
 
1232
        if(add) {
1233
            fragmentHashMap.put(fragmentKeyNuevo, fragment);
1234
 
1235
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
1236
            fragmentTransaction.add(R.id.fragment_container, fragment, fragmentKeyNuevo);
1237
            fragmentTransaction.commitAllowingStateLoss();
1238
        }
1239
 
1240
 
1241
        if(fragment != null) {
1242
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
1243
            fragmentTransaction.show(fragment);
1244
            fragmentTransaction.commitAllowingStateLoss();
1245
        }
1246
 
1247
    }
1248
 
1249
    @Override
1250
    public void changeTopicActive(String topicUuid)
1251
    {
1252
        Log.d(TAG, "changeTopicActive : " + topicUuid);
1253
       // Log.e("Guardo", "Topico en Main");
1254
 
1255
        preference.setTopicUuidActive(topicUuid);
1256
        preference.setCapsuleUuidActive("");
1257
        preference.setSlideUuidActive("");
1258
        preference.save();
1259
 
1260
        invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
1261
    }
1262
 
1263
    @Override
1264
    public void changeCapsuleActive(String capsuleUuid)
1265
    {
1266
        Log.d(TAG, "changeCapsuleActive : " + capsuleUuid);
1267
 
1268
 
1269
 
1270
        preference.setCapsuleUuidActive(capsuleUuid);
1271
        preference.setSlideUuidActive("");
1272
        preference.save();
1273
 
1274
        invokeFragment(Constants.IDX_FRAGMENT_SLIDES);
1275
    }
1276
 
1277
    @Override
1278
    public void changeCompanyActive(String companyUuid)
1279
    {
1280
        Log.d(TAG, "changeCompanyActive : " + companyUuid);
1281
 
1282
        preference.setCompanyUuidActive(companyUuid);
1283
        preference.save();
1284
    }
1285
 
1286
    @Override
1287
    public synchronized void changeSlideActive(String slideUuid, String type, boolean showGallery)
1288
    {
1289
 
1290
        Log.d(TAG, "changeSlideActive : " + slideUuid);
1291
 
1292
        if(!preference.getSlideUuidActive().equals(slideUuid) && type.equals(Constants.SLIDE_TYPE_IMAGE)) {
1293
            Log.d(TAG, "registerOnPageChangeCallback - createProgressAndSyncRecord");
1294
 
1295
            createProgressAndSyncRecord(slideUuid, true, false, false);
1296
        }
1297
        preference.setSlideUuidActive(slideUuid);
1298
        preference.save();
1299
 
1300
 
1301
        if(showGallery) {
1302
            invokeFragment(Constants.IDX_FRAGMENT_GALLERY);
1303
 
1304
        }
1305
    }
1306
 
1307
    @Override
1308
    public String getTopicUuidActive()
1309
    {
1310
        return preference.getTopicUuidActive();
1311
    }
1312
 
1313
    @Override
1314
    public String getCapsuleUuidActive()
1315
    {
1316
        return preference.getCapsuleUuidActive();
1317
    }
1318
 
1319
    @Override
1320
    public String getSlideUuidActive()
1321
    {
1322
        return preference.getSlideUuidActive();
1323
    }
1324
 
1325
    @Override
1326
    public String getCompanyUuidActive()
1327
    {
1328
        return preference.getCompanyUuidActive();
1329
    }
1330
 
1331
    @Override
1332
    public void setTitleActionBar(String title)
1333
    {
1334
 
1335
        getSupportActionBar().setTitle(title);
1336
    }
1337
 
1338
    @Override
1339
    public synchronized void createProgressAndSyncRecord(String slideUuid, boolean completed, boolean isQuiz, boolean isAudioOrVideo)
1340
    {
1341
        Calendar calendar = Calendar.getInstance();
1342
        Date date = calendar.getTime();
1343
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1344
        String  dateOn = simpleDateFormat.format(date);
1345
 
1346
        SlideDao slideDao = mAppDatabase.getSlideDao();
1347
        Slide slide =  slideDao.selectByUuid(slideUuid);
1348
 
1349
        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1350
        Capsule capsule = capsuleDao.selectByUuid(slide.getCapsuleUuid());
1351
 
1352
        TopicDao topicDao = mAppDatabase.getTopicDao();
1353
        Topic topic = topicDao.selectByUuid(capsule.getTopicUuid());
1354
 
1355
        UserLog userLog;
1356
        UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1357
 
1358
        SyncDao syncDao = mAppDatabase.getSyncDao();
1359
        Sync sync;
1360
 
1361
        String userUuid = preference.getUserUuid();
1362
 
1363
        // Progreso y UserLog  del Slide
1364
        ProgressDao progressDao = mAppDatabase.getProgressDao();
1365
        Progress progressSlide = progressDao.selectBySlideUuidAndUserUuid(slide.getUuid(), userUuid);
1366
        Progress progressCapsule =  progressDao.selectByCapsuleUuidAndUserUuid(slide.getCapsuleUuid(),userUuid);
1367
        Progress progressTopic =  progressDao.selectByTopicUuidAndUserUuid(slide.getTopicUuid(),userUuid);
1368
 
1369
        int totalSlides = 0;
1370
        int viewSlides = 0;
1371
        double percentaje = 0;
1372
        boolean newRecord = false;
1373
        boolean retakeQuiz = false;
1374
 
1375
        /*** INICIO PROCESO DIAPOSITIVA ***/
1376
        if(progressSlide == null) {
1377
 
1378
            retakeQuiz = false;
1379
 
1380
 
1381
            progressSlide = new Progress();
1382
            progressSlide.setUserUuid(preference.getUserUuid());
1383
            progressSlide.setCompanyUuid(topic.getCompanyUuid());
1384
            progressSlide.setTopicUuid(topic.getUuid());
1385
            progressSlide.setCapsuleUuid(capsule.getUuid());
1386
            progressSlide.setSlideUuid(slide.getUuid());
1387
            progressSlide.setType(Constants.PROGERSS_TYPE_SLIDE);
1388
            progressSlide.setCompleted(completed ? 1 : 0);
1389
            progressSlide.setAddedOn(dateOn);
1390
            progressSlide.setUpdatedOn(dateOn);
1391
            progressDao.insert(progressSlide);
1392
        } else {
1393
            retakeQuiz = true;
1394
 
1395
            if (progressSlide.getCompleted() == 1) {
1396
                progressSlide.setReturningAfterCompleted(progressSlide.getReturningAfterCompleted() + 1);
1397
            } else {
1398
                if (completed) {
1399
                    //0 y 1 para Boolean
1400
                    progressSlide.setCompleted(completed  ? 1 : 0);
1401
                } else {
1402
                    progressSlide.setReturning(progressSlide.getReturning() + 1);
1403
                }
1404
            }
1405
 
1406
            progressSlide.setUpdatedOn(dateOn);
1407
            progressDao.update(progressSlide);
1408
        }
1409
 
1410
 
1411
 
1412
        /*** FIN PROCESO DIAPOSITIVA ***/
1413
 
1414
 
1415
 
1416
        /*** INICIO PROCESO TOPICO ***/
1417
        ResultCount resultCount;
1418
 
1419
 
1420
        resultCount = slideDao.getCountByTopicUuid(slide.getTopicUuid());
1421
        totalSlides = resultCount.getCount();
1422
 
1423
        resultCount = progressDao.getCountSlidesCompletedByTopicUuidAndUserUuid(slide.getTopicUuid(), userUuid);
1424
        viewSlides =  resultCount.getCount();
1425
        if(totalSlides == 0) {
1426
            percentaje = 0;
1427
        } else {
1428
            percentaje = (viewSlides * 100) / totalSlides;
1429
        }
1430
 
1431
        if(progressTopic == null) {
1432
            newRecord = true;
1433
            progressTopic = new Progress();
1434
            progressTopic.setUserUuid(preference.getUserUuid());
1435
            progressTopic.setCompanyUuid( topic.getCompanyUuid());
1436
            progressTopic.setTopicUuid (topic.getUuid());
1437
 
1438
            progressTopic.setViewSlides(viewSlides);
1439
            progressTopic.setTotalSlides(totalSlides);
1440
            progressTopic.setProgress (percentaje);
1441
            progressTopic.setType(Constants.PROGERSS_TYPE_TOPIC);
1442
 
1443
            progressTopic.setAddedOn(dateOn);
1444
            progressTopic.setUpdatedOn(dateOn);
1445
             progressDao.insert(progressTopic);
1446
        } else {
1447
            newRecord = false;
1448
            progressTopic.setViewSlides(viewSlides);
1449
            progressTopic.setTotalSlides(totalSlides);
1450
            progressTopic.setProgress (percentaje);
1451
            progressDao.update(progressTopic);
1452
        }
1453
 
1454
        try {
1455
            JSONObject json = progressTopic.toJson();
1456
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1457
 
1458
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1459
            syncDao.insert(sync);
1460
        } catch (JSONException e) {
1461
        }
1462
 
1463
        if(newRecord) {
1464
            userLog = new UserLog();
1465
            userLog.setUserUuid(preference.getUserUuid());
1466
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_TOPIC);
1467
            userLog.setCompanyUuid (topic.getCompanyUuid());
1468
            userLog.setTopicUuid (topic.getUuid());
1469
            userLog.setAddedOn(dateOn);
1470
 
1471
 
1472
            userLogDao.insert(userLog);
1473
            try {
1474
                JSONObject json = userLog.toJson();
1475
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1476
 
1477
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1478
                syncDao.insert(sync);
1479
            } catch (JSONException e) {
1480
            }
1481
        }
1482
        /*** FIN PROCESO TOPICO ***/
1483
 
1484
 
1485
 
1486
        /*** INICIO PROCESO CAPSULA ***/
1487
        resultCount = slideDao.getCountByCapsuleUuid(slide.getCapsuleUuid());
1488
        totalSlides = resultCount.getCount();
1489
        resultCount = progressDao.getCountSlidesCompletedByCapsuleUuidAndUserUuid(slide.getCapsuleUuid(), userUuid);
1490
        viewSlides =  resultCount.getCount();
1491
        if(totalSlides == 0) {
1492
            percentaje = 0;
1493
        } else {
1494
            percentaje = (viewSlides * 100) / totalSlides;
1495
        }
1496
 
1497
        if(progressCapsule == null) {
1498
            newRecord = true;
1499
            progressCapsule = new Progress();
1500
            progressCapsule.setUserUuid(preference.getUserUuid());
1501
            progressCapsule.setCompanyUuid(topic.getCompanyUuid());
1502
            progressCapsule.setTopicUuid(topic.getUuid());
1503
            progressCapsule.setCapsuleUuid (capsule.getUuid());
1504
            progressCapsule.setViewSlides(viewSlides);
1505
            progressCapsule.setTotalSlides(totalSlides);
1506
            progressCapsule.setProgress(percentaje);
1507
            progressCapsule.setType(Constants.PROGERSS_TYPE_CAPSULE);
1508
            progressCapsule.setAddedOn(dateOn);
1509
            progressCapsule.setUpdatedOn(dateOn);
1510
            progressDao.insert(progressCapsule);
1511
 
1512
            Log.d(TAG, "Progress Capsule Nueva : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1513
            preference.setLastCapsuleUuidActive(capsule.getUuid());
1514
        } else {
1515
            newRecord = false;
1516
            progressCapsule.setViewSlides(viewSlides);
1517
            progressCapsule.setTotalSlides(totalSlides);
1518
            progressCapsule.setProgress(percentaje);
1519
 
1520
            Log.d(TAG, "Progress Capsule : getLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1521
            Log.d(TAG, "Progress Capsule : CapsuleActive : " + preference.getCapsuleUuidActive());
1522
 
1523
            if (!preference.getLastCapsuleUuidActive().equals(preference.getCapsuleUuidActive())) {
1524
 
1525
                Log.d(TAG, "Capsule Progress : " + progressCapsule.getProgress());
1526
                Log.d(TAG, "Capsule Completed : " + progressCapsule.getCompleted());
1527
                Log.d(TAG, "Capsule Total slides : " + progressCapsule.getTotalSlides());
1528
                Log.d(TAG, "Capsule View slides : " + progressCapsule.getViewSlides());
1529
 
1530
                if(progressCapsule.getCompleted() == 1) {
1531
                    Log.d(TAG, "Capsule OLD returningAfterCompleted = " + progressCapsule.getReturningAfterCompleted());
1532
 
1533
                    int returningAfterCompleted = progressCapsule.getReturningAfterCompleted() + 1;
1534
 
1535
                    Log.d(TAG, "Capsule NEW returningAfterCompleted = " + returningAfterCompleted);
1536
                    progressCapsule.setReturningAfterCompleted(returningAfterCompleted);
1537
                }
1538
 
1539
                preference.setLastCapsuleUuidActive(capsule.getUuid());
1540
                preference.save();
1541
 
1542
                Log.d(TAG, "Progress Capsule : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1543
            }
1544
 
1545
            progressDao.update(progressCapsule);
1546
        }
1547
        try {
1548
            JSONObject json = progressCapsule.toJson();
1549
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1550
 
1551
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1552
            syncDao.insert(sync);
1553
        } catch (JSONException e) {
1554
 
1555
        }
1556
 
1557
        if(newRecord) {
1558
            userLog = new UserLog();
1559
            userLog.setUserUuid(preference.getUserUuid());
1560
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_CAPSULE);
1561
            userLog.setCompanyUuid(topic.getCompanyUuid());
1562
            userLog.setTopicUuid(topic.getUuid());
1563
            userLog.setCapsuleUuid(capsule.getUuid());
1564
            userLog.setAddedOn(dateOn);
1565
 
1566
 
1567
            userLogDao.insert(userLog);
1568
            try {
1569
                JSONObject json = userLog.toJson();
1570
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1571
 
1572
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1573
                syncDao.insert(sync);
1574
            } catch (JSONException e) {
1575
            }
1576
        }
1577
 
1578
 
1579
        /*** FIN PROCESO CAPSULA ***/
1580
 
1581
        /*** INICIO USERLOG SLIDE ***/
1582
        userLog = new UserLog();
1583
        userLog.setUserUuid(preference.getUserUuid());
1584
        userLog.setActivity(Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1585
        userLog.setCompanyUuid(topic.getCompanyUuid());
1586
        userLog.setTopicUuid(topic.getUuid());
1587
        userLog.setCapsuleUuid(capsule.getUuid());
1588
        userLog.setSlideUuid(slide.getUuid());
1589
        userLog.setAddedOn(dateOn);
1590
 
1591
 
1592
        userLogDao.insert(userLog);
1593
        try {
1594
            JSONObject json = userLog.toJson();
1595
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1596
 
1597
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1598
            syncDao.insert(sync);
1599
        } catch (JSONException e) {
1600
        }
1601
 
1602
        /*** FIN ***/
1603
 
1604
 
1605
        /*** PROGRESS SLIDE***/
1606
        try {
1607
            JSONObject json = progressSlide.toJson();
1608
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1609
 
1610
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1611
            syncDao.insert(sync);
1612
        } catch (JSONException e) {
1613
        }
1614
 
1615
        /** IS SLIDE = QUIZ **/
1616
        if (isQuiz) {
1617
            userLog = new UserLog();
1618
            userLog.setUserUuid(preference.getUserUuid());
1619
            userLog.setActivity(retakeQuiz ? Constants.USER_LOG_ACTIVITY_RETAKE_A_TEST : Constants.USER_LOG_ACTIVITY_TAKE_A_TEST);
1620
            userLog.setCompanyUuid (topic.getCompanyUuid());
1621
            userLog.setTopicUuid(slide.getTopicUuid());
1622
            userLog.setCapsuleUuid(slide.getCapsuleUuid());
1623
            userLog.setSlideUuid(slide.getUuid());
1624
            userLog.setAddedOn(dateOn);
1625
 
1626
            userLogDao.insert(userLog);
1627
            try {
1628
                JSONObject json = userLog.toJson();
1629
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1630
 
1631
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1632
                syncDao.insert(sync);
1633
            } catch (JSONException e) {
1634
            }
1635
 
1636
 
1637
            if(progressSlide.getCompleted() == 1) {
1638
                userLog = new UserLog();
1639
                userLog.setUserUuid(preference.getUserUuid());
1640
                userLog.setActivity(Constants.USER_LOG_ACTIVITY_APPROVED_TEST);
1641
                userLog.setCompanyUuid(topic.getCompanyUuid());
1642
                userLog.setTopicUuid(slide.getTopicUuid());
1643
                userLog.setCapsuleUuid(slide.getCapsuleUuid());
1644
                userLog.setSlideUuid(slide.getUuid());
1645
                userLog.setAddedOn(dateOn);
1646
 
1647
                userLogDao.insert(userLog);
1648
                try {
1649
                    JSONObject json = userLog.toJson();
1650
                    json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1651
 
1652
                    sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1653
                    syncDao.insert(sync);
1654
                } catch (JSONException e) {
1655
                }
1656
 
1657
            } else {
1658
                if(progressSlide.getCompleted() == 1) {
1659
                    userLog = new UserLog();
1660
                    userLog.setUserUuid(preference.getUserUuid());
1661
                    userLog.setActivity( Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1662
                    userLog.setCompanyUuid(topic.getCompanyUuid());
1663
                    userLog.setTopicUuid(slide.getTopicUuid());
1664
                    userLog.setCapsuleUuid(slide.getCapsuleUuid());
1665
                    userLog.setSlideUuid(slide.getUuid());
1666
                    userLog.setAddedOn(dateOn);
1667
 
1668
                    userLogDao.insert(userLog);
1669
                    try {
1670
                        JSONObject json = userLog.toJson();
1671
                        json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1672
 
1673
                        sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1674
                        syncDao.insert(sync);
1675
                    } catch (JSONException e) {
1676
                    }
1677
                }
1678
            }
1679
        }
1680
 
1681
        requestExecuteSyncAdapter();
1682
    }
1683
 
1684
    @Override
1685
    public void launchVideoViewer(String videoAudioUrl)
1686
    {
1687
 
1688
        Intent intent = new Intent(getApplicationContext(), VideoAudioActivity.class);
1689
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1690
        intent.putExtra("deviceId", preference.getDeviceUuid());
1691
        intent.putExtra("password", preference.getPassword());
1692
        //startActivityForResult(intent, Constants.REQUEST_CODE_VIDEO);
1693
 
1694
        mLauncher.launch(intent);
1695
 
1696
    }
1697
 
1698
    @Override
1699
    public void launchAudioViewer(String videoAudioUrl)
1700
    {
1701
 
1702
        Intent intent = new Intent(getApplicationContext(), VideoAudioActivity.class);
1703
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1704
        intent.putExtra("deviceId", preference.getDeviceUuid());
1705
        intent.putExtra("password", preference.getPassword());
1706
        //startActivityForResult(intent, Constants.REQUEST_CODE_AUDIO);
1707
 
1708
 
1709
        mLauncher.launch(intent);
1710
    }
1711
 
1712
    @Override
1713
    public void launchTextViewer(String description)
1714
    {
1715
        Intent intent = new Intent(getApplicationContext(),TextActivity.class);
1716
        intent.putExtra("description",description);
1717
 
1718
        //startActivityForResult(intent, Constants.REQUEST_CODE_TEXT);
1719
 
1720
        mLauncher.launch(intent);
1721
    }
1722
 
1723
 
1724
    @Override
1725
    public void launchDocumentViewer(String file)
1726
    {
1727
 
1728
        Intent intent = new Intent(getApplicationContext(),PdfActivity.class);
1729
        intent.putExtra("documentUrl",file);
1730
        intent.putExtra("deviceId", preference.getDeviceUuid());
1731
        intent.putExtra("password", preference.getPassword());
1732
 
1733
        //startActivityForResult(intent, Constants.REQUEST_CODE_PDF);
1734
 
1735
        mLauncher.launch(intent);
1736
    }
1737
 
1738
    @Override
1739
    public void launchQuizViewer(String quizUuid)
1740
    {
1741
        ProgressDao progressDao = mAppDatabase.getProgressDao();
1742
        Progress progress = progressDao.selectBySlideUuidAndUserUuid(preference.getSlideUuidActive(), preference.getUserUuid());
1743
 
1744
        boolean launch = false;
1745
        if(progress != null && progress.getCompleted() == 0) {
1746
 
1747
            Calendar calendar = Calendar.getInstance();
1748
            Date date = calendar.getTime();
1749
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1750
            try {
1751
                Long updateOn = simpleDateFormat.parse(progress.getUpdatedOn()).getTime();
1752
 
1753
                //30 minutes
1754
                long mintime = 30 * 60 * 1000;
1755
                if(date.getTime() - updateOn >  mintime ) {
1756
                    launch = true;
1757
                }
1758
 
1759
                launch = true;
1760
 
1761
            } catch(Exception e) {
1762
 
1763
            }
1764
 
1765
 
1766
        } else {
1767
            launch = true;
1768
        }
1769
 
1770
        if(launch) {
1771
 
1772
            QuizDao quizDao = mAppDatabase.getQuizDao();
1773
            Quiz quiz = quizDao.selectByUuid(quizUuid);
1774
 
1775
            TopicDao topicDao = mAppDatabase.getTopicDao();
1776
            Topic topic = topicDao.selectByUuid(preference.getTopicUuidActive());
1777
 
1778
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1779
            Capsule capsule = capsuleDao.selectByUuid(preference.getCapsuleUuidActive());
1780
 
1781
            SlideDao slideDao = mAppDatabase.getSlideDao();
1782
            Slide slide = slideDao.selectByUuid(preference.getSlideUuidActive());
1783
 
1784
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1785
            List<Question> questions = questionDao.selectAllByQuizUuid(quiz.getUuid());
1786
 
1787
 
1788
            List<Answer> answers;
1789
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1790
 
1791
            Intent intent = new Intent(getApplicationContext(), QuizActivity.class);
1792
           // intent.putExtra("companyUuid", topic.getCompanyUuid());
1793
           // intent.putExtra("topicUuid", topic.getUuid());
1794
            //intent.putExtra("capsuleUuid", capsule.getUuid());
1795
            //intent.putExtra("slideUuid", slide.getUuid());
1796
            //intent.putExtra("userUuid", preference.getUserUuid());
1797
            //intent.putExtra("quizUuid", quizUuid);
1798
 
1799
 
1800
            intent.putExtra("quiz_uuid", quiz.getUuid());
1801
            intent.putExtra("quiz_company_uuid", quiz.getCompanyUuid());
1802
            intent.putExtra("quiz_name", quiz.getName());
1803
            intent.putExtra("quiz_points", quiz.getPoints());
1804
            intent.putExtra("quiz_max_time", quiz.getMaxTime());
1805
            intent.putExtra("quiz_minimum_points_required", quiz.getMinimumPointsRequired());
1806
            intent.putExtra("quiz_failed", quiz.getFailed());
1807
            intent.putExtra("quiz_text", quiz.getText());
1808
 
1809
            intent.putExtra("questions", questions.size());
1810
            int i = 1;
1811
            int j = 1;
1812
            for(Question question : questions) {
1813
                intent.putExtra("question" + i + "_uuid", question.getUuid());
1814
                intent.putExtra("question" + i + "_text", question.getText());
1815
                intent.putExtra("question" + i + "_max_length", question.getMaxlength());
1816
                intent.putExtra("question" + i + "_position", question.getPosition());
1817
                intent.putExtra("question" + i + "_points", question.getPoints());
1818
                intent.putExtra("question" + i + "_type", question.getType());
1819
 
1820
                answers = answerDao.selectAllByQuestionUuid(question.getUuid());
1821
                intent.putExtra("question" + i + "_answers", answers.size());
1822
 
1823
                j = 1;
1824
                for(Answer answer : answers) {
1825
                    intent.putExtra("question" + i + "_answer_uuid" + j, answer.getUuid());
1826
                    intent.putExtra("question" + i + "_answer_text" + j, answer.getText());
1827
                    intent.putExtra("question" + i + "_answer_points" + j, answer.getPoints());
1828
                    intent.putExtra("question" + i + "_answer_correct" + j, answer.getCorrect());
1829
                    j++;
1830
                }
1831
 
1832
                i++;
1833
            }
1834
 
1835
 
1836
 
1837
            //startActivityForResult(intent, Constants.REQUEST_CODE_QUIZ);
1838
 
1839
            mLauncher.launch(intent);
1840
        } else {
1841
            showMessageSnackBar(getString(R.string.error_retry_quiz_min_time));
1842
        }
1843
    }
1844
 
1845
 
1846
    @Override
1847
    public Preference getPreference() {
1848
        return preference;
1849
    }
1850
 
1851
 
1852
 
1853
 
1854
    public void requestCheckChanges()
1855
    {
1856
        Log.d(TAG, "requestCheckChanges");
1857
        try {
1858
 
1859
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1860
            List<Capsule> capsules = capsuleDao.selectAll();
1861
 
1862
            if(capsules.size() > 0) {
1863
                //ArrayList<String> ids = new ArrayList<>();
1864
 
1865
                TimeZone timeZone = TimeZone.getTimeZone("UTC");
1866
                Calendar calendar = Calendar.getInstance(timeZone);
1867
                TimeZone tz = calendar.getTimeZone();
1868
                int created =  (int) (calendar.getTimeInMillis() / 1000);
1869
 
1870
                Random random = new Random(created);
1871
                int rand = 1000 + random.nextInt(8999);
1872
 
1873
 
1874
                //Log.d("requestCheckChanges", "token = " + preference.getDeviceUuid());
1875
                //Log.d("requestCheckChanges", "created = " + created);
1876
               // Log.d("requestCheckChanges", "rand = " + rand);
1877
                //Log.d("requestCheckChanges", "calc = " + preference.password + ':' +  created + ':' + rand);
1878
 
1879
                String secret = MD5.generar(preference.getPassword() + ':' +  created + ':' + rand);
1880
 
1881
                //Log.d("requestCheckChanges", "secret = " + secret);
1882
 
1883
 
1884
                FormBody.Builder formBodyCheckChangeBuilder = new FormBody.Builder();
1885
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_DEVICE_UUID, preference.getDeviceUuid());
1886
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_DATE_CHANGES, preference.getMaxDateChanges());
1887
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_IS_FOREGROUND, String.valueOf(isForeground ? 1 : 0));
1888
                Http http = new Http(this.getCacheDir(), preference.getDeviceUuid(), secret, created, rand);
1889
                OkHttpClient client = http.getHttpClient(false);
1890
 
1891
 
1892
 
1893
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(capsules.size()));
1894
                //formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(0));
1895
 
1896
              int i = 1;
1897
                for(Capsule capsule : capsules)
1898
                {
1899
                    Log.d("requestCheckChanges", "id" + i + " = " + capsule.getTopicUuid() + "|" + capsule.getUuid());
1900
 
1901
 
1902
                    formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_ID + i, capsule.getTopicUuid() + "|" + capsule.getUuid());
1903
                    i++;
1904
                }
1905
 
1906
 
1907
 
1908
                RequestBody formBody = formBodyCheckChangeBuilder.build();
1909
 
1910
                Log.d(TAG, "URL = " + Configuration.URL_CHECK_CHANGES);
1911
                Request request = new Request.Builder()
1912
                        .url(Configuration.URL_CHECK_CHANGES)
1913
                        .post(formBody)
1914
                        .build();
1915
 
1916
                Call call = client.newCall(request);
7 gabriel 1917
                call.enqueue(new Callback() {
1 gabriel 1918
                    public void onResponse(Call call, Response response)
1919
                            throws IOException {
1920
 
1921
 
1922
 
1923
                        processResponseServerChanges(response.body().string());
1924
                    }
1925
 
1926
                    public void onFailure(Call call, IOException e) {
1927
                        Log.d(TAG, "Error :  " +  e.getMessage());
1928
                    }
1929
                });
1930
            }
1931
 
1932
 
1933
 
1934
        } catch(Exception e) {
1935
 
1936
        }
1937
    }
1938
 
1939
 
1940
    public void syncFromServer(JSONObject data)
1941
    {
1942
        try {
1943
            JSONObject objUser = data.getJSONObject("user");
1944
            String userUuid = objUser.getString("uuid");
1945
 
1946
 
1947
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1948
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1949
            QuizDao quizDao = mAppDatabase.getQuizDao();
1950
            SlideDao slideDao = mAppDatabase.getSlideDao();
1951
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1952
            TopicDao topicDao = mAppDatabase.getTopicDao();
1953
            CompanyDao companyDao = mAppDatabase.getCompanyDao();
1954
            UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
1955
 
1956
 
1957
 
1958
            ProgressDao progressDao = mAppDatabase.getProgressDao();
1959
            progressDao.removeAllUserUuidNotEqual(userUuid);
1960
 
1961
 
1962
            UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1963
            userLogDao.removeAllUserUuidNotEqual(userUuid);
1964
 
1965
            JSONArray arrayCapsules;
1966
            JSONArray arraySlides;
1967
            JSONArray arrayAnswers;
1968
            JSONArray arrayQuestions;
1969
            JSONArray arrayProgress;
1970
            JSONArray arrayQuizzes;
1971
            JSONArray arrayUserLog;
1972
 
1973
            JSONObject objTopic;
1974
            JSONObject objCapsule;
1975
            JSONObject objSlide;
1976
            JSONObject objAnswer;
1977
            JSONObject objQuestion;
1978
            JSONObject objQuiz;
1979
            JSONObject objProgress;
1980
            JSONObject objUserLog;
1981
            int i,j,x;
1982
 
1983
            if(data.has("progress")) {
1984
 
1985
                arrayProgress = data.getJSONArray("progress");
1986
                for (i = 0; i < arrayProgress.length(); i++) {
1987
                    objProgress = arrayProgress.getJSONObject(i);
1988
 
1989
 
1990
                    Progress progress = null;
1991
 
1992
 
1993
                    userUuid = objProgress.getString("user_uuid");
1994
                    String type = objProgress.getString("type");
1995
                    String topicUuid = objProgress.getString("topic_uuid");
1996
                    String capsuleUuid = objProgress.getString("capsule_uuid");
1997
                    String slideUuid = objProgress.getString("slide_uuid");
1998
 
1999
                    if(type == Constants.PROGERSS_TYPE_SLIDE) {
2000
                        progress = progressDao.selectBySlideUuidAndUserUuid(slideUuid, userUuid);
2001
                    } else if(type == Constants.PROGERSS_TYPE_CAPSULE) {
2002
                        progress = progressDao.selectByCapsuleUuidAndUserUuid(capsuleUuid, userUuid);
2003
                    } else if(type == Constants.PROGERSS_TYPE_TOPIC) {
2004
                        progress = progressDao.selectByTopicUuidAndUserUuid(topicUuid, userUuid);
2005
                    }
2006
 
2007
 
2008
                    if(progress == null) {
2009
                        progress = new Progress();
2010
                        progress.setUserUuid(userUuid);
2011
                        progress.setCompanyUuid(objProgress.getString("company_uuid"));
2012
                        progress.setTopicUuid(topicUuid);
2013
                        progress.setCapsuleUuid(capsuleUuid);
2014
                        progress.setSlideUuid(slideUuid);
2015
                        progress.setProgress(objProgress.getDouble("progress"));
2016
                        progress.setTotalSlides(objProgress.getInt("total_slides"));
2017
                        progress.setViewSlides(objProgress.getInt("view_slides"));
2018
                        progress.setType(type);
2019
                        progress.setReturning(objProgress.getInt("returning"));
2020
                        progress.setReturningAfterCompleted(objProgress.getInt("returning_after_completed"));
2021
                        progress.setCompleted(objProgress.getInt("completed"));
2022
                        progress.setAddedOn(objProgress.getString("added_on"));
2023
                        progress.setUpdatedOn(objProgress.getString("updated_on"));
2024
 
2025
                        progressDao.insert(progress);
2026
                    }
2027
 
2028
 
2029
                }
2030
            }
2031
 
2032
            if(data.has("userlog")) {
2033
                arrayUserLog = data.getJSONArray("userlog");
2034
                for (i = 0; i < arrayUserLog.length(); i++) {
2035
                    objUserLog = arrayUserLog.getJSONObject(i);
2036
 
2037
                    userUuid = objUserLog.getString("user_uuid");
2038
                    String activity = objUserLog.getString("activity");
2039
                    String added_on = objUserLog.getString("added_on");
2040
 
2041
                    UserLog userLog = userLogDao.selectOneByUserUuidAndActivityAndAddedOn(userUuid, activity, added_on);
2042
                    if(userLog == null) {
2043
                        userLog = new UserLog();
2044
                        userLog.setUserUuid(objUserLog.getString("user_uuid"));
2045
                        userLog.setCompanyUuid(objUserLog.getString("company_uuid"));
2046
                        userLog.setTopicUuid(objUserLog.getString("topic_uuid"));
2047
                        userLog.setCapsuleUuid(objUserLog.getString("capsule_uuid"));
2048
                        userLog.setSlideUuid(objUserLog.getString("slide_uuid"));
2049
                        userLog.setActivity(objUserLog.getString("activity"));
2050
                        userLog.setAddedOn(objUserLog.getString("added_on"));
2051
                        userLogDao.insert(userLog);
2052
                    }
2053
                }
2054
            }
2055
 
2056
            String uuid;
2057
            Company company;
2058
            if(data.has("quizzes")) {
2059
                Quiz quiz;
2060
                Question question;
2061
                Answer answer;
2062
 
2063
                arrayQuizzes = data.getJSONArray("quizzes");
2064
                for (i = 0; i < arrayQuizzes.length(); i++) {
2065
                    objQuiz = arrayQuizzes.getJSONObject(i);
2066
                    uuid = objQuiz.getString("company_uuid");
2067
                    company = companyDao.selectByUuid(uuid);
2068
                    if (company == null) {
2069
                        company = new Company();
2070
                        company.setUuid(objQuiz.getString("company_uuid"));
2071
                        company.setName(objQuiz.getString("company_name"));
2072
                        company.setImage(objQuiz.getString("company_image"));
2073
 
2074
                        companyDao.insert(company);
2075
                    } else {
2076
                        company.setName(objQuiz.getString("company_name"));
2077
                        company.setImage(objQuiz.getString("company_image"));
2078
 
2079
                        companyDao.update(company);
2080
                    }
2081
 
2082
                    uuid =  objQuiz.getString("uuid");
2083
                    quiz = quizDao.selectByUuid(uuid);
2084
 
2085
                    if(quiz == null) {
2086
                        quiz = new Quiz();
2087
                        quiz.setUuid(  objQuiz.getString("uuid"));
2088
                        quiz.setCompanyUuid(  company.getUuid() );
2089
                        quiz.setFailed(  objQuiz.getString("failed"));
2090
                        quiz.setName(  objQuiz.getString("name"));
2091
                        quiz.setText(  objQuiz.getString("text"));
2092
                        quiz.setPoints(  objQuiz.getInt("points"));
2093
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2094
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2095
                        quizDao.insert(quiz);
2096
 
2097
                    } else {
2098
                        quiz.setCompanyUuid(  company.getUuid() );
2099
                        quiz.setFailed(  objQuiz.getString("failed"));
2100
                        quiz.setName(  objQuiz.getString("name"));
2101
                        quiz.setText(  objQuiz.getString("text"));
2102
                        quiz.setPoints(  objQuiz.getInt("points"));
2103
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2104
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2105
                        quizDao.update(quiz);
2106
                    }
2107
 
2108
                    arrayQuestions = objQuiz.getJSONArray("questions");
2109
                    for (j = 0; j < arrayQuestions.length(); j++) {
2110
                        objQuestion = arrayQuestions.getJSONObject(j);
2111
 
2112
                        uuid = objQuestion.getString("uuid");
2113
                        question = questionDao.selectByUuid(uuid);
2114
                        if(question == null) {
2115
                            question = new Question();
2116
                            question.setQuizUuid( quiz.getUuid());
2117
                            question.setUuid(uuid) ;
2118
                            question.setText( objQuestion.getString("text"));
2119
                            question.setType( objQuestion.getString("type"));
2120
                            question.setPoints( objQuestion.getInt("points"));
2121
                            question.setMaxlength( objQuestion.getInt("maxlength"));
2122
 
2123
                            questionDao.insert(question);
2124
                        } else {
2125
                            question.setQuizUuid( quiz.getUuid());
2126
                            question.setText( objQuestion.getString("text"));
2127
                            question.setType( objQuestion.getString("type"));
2128
                            question.setPoints( objQuestion.getInt("points"));
2129
                            question.setMaxlength( objQuestion.getInt("maxlength"));
2130
 
2131
                            questionDao.update(question);
2132
                        }
2133
 
2134
 
2135
 
2136
 
2137
                        arrayAnswers = objQuestion.getJSONArray("answers");
2138
                        for (x = 0; x < arrayAnswers.length(); x++) {
2139
                            objAnswer = arrayAnswers.getJSONObject(x);
2140
 
2141
                            uuid = objAnswer.getString("uuid");
2142
                            answer = answerDao.selectByUuid(uuid);
2143
 
2144
                            if(answer == null) {
2145
 
2146
                                answer = new Answer();
2147
                                answer.setQuestionUuid(question.getUuid());
2148
                                answer.setUuid(uuid);
2149
                                answer.setText(objAnswer.getString("text"));
2150
                                answer.setPoints(objAnswer.getInt("points"));
2151
                                answer.setCorrect(objAnswer.getString("correct"));
2152
 
2153
                                answerDao.insert(answer);
2154
                            } else {
2155
                                answer.setQuestionUuid(question.getUuid());
2156
                                answer.setText(objAnswer.getString("text"));
2157
                                answer.setPoints(objAnswer.getInt("points"));
2158
                                answer.setCorrect(objAnswer.getString("correct"));
2159
                                answerDao.update(answer);
2160
                            }
2161
                        }
2162
                    }
2163
                }
2164
            }
2165
 
2166
 
2167
 
2168
 
2169
 
2170
            if(data.has("topics")) {
2171
                Topic topic;
2172
                Capsule capsule;
2173
                Slide slide;
2174
 
2175
                JSONArray arrayTopics = data.getJSONArray("topics");
2176
                for (i = 0; i < arrayTopics.length(); i++) {
2177
                    objTopic = arrayTopics.getJSONObject(i);
2178
 
2179
                    uuid = objTopic.getString("company_uuid");
2180
                    company = companyDao.selectByUuid(uuid);
2181
                    if (company == null) {
2182
                        company = new Company();
2183
                        company.setUuid(objTopic.getString("company_uuid"));
2184
                        company.setName(objTopic.getString("company_name"));
2185
                        company.setImage(objTopic.getString("company_image"));
2186
 
2187
                        companyDao.insert(company);
2188
                    } else {
2189
                        company.setName(objTopic.getString("company_name"));
2190
                        company.setImage(objTopic.getString("company_image"));
2191
 
2192
                        companyDao.update(company);
2193
                    }
2194
 
2195
                    uuid = objTopic.getString("uuid");
2196
                    topic = topicDao.selectByUuid(uuid);
2197
 
2198
                    if (topic == null) {
2199
                        topic = new Topic();
2200
                        topic.setUuid(uuid);
2201
                        topic.setCompanyUuid(company.getUuid());
2202
                        topic.setName(objTopic.getString("name"));
2203
                        topic.setDescription(objTopic.getString("description"));
2204
                        topic.setImage(objTopic.getString("image"));
2205
                        topic.setPosition(objTopic.getInt("position"));
2206
                        topicDao.insert(topic);
2207
                    } else {
2208
                        topic.setCompanyUuid(company.getUuid());
2209
                        topic.setName(objTopic.getString("name"));
2210
                        topic.setDescription(objTopic.getString("description"));
2211
                        topic.setImage(objTopic.getString("image"));
2212
                        topic.setPosition(objTopic.getInt("position"));
2213
                        topicDao.update(topic);
2214
                    }
2215
 
2216
 
2217
 
2218
 
2219
 
2220
                    arrayCapsules = objTopic.getJSONArray("capsules");
2221
                  //  Log.e("Objeto:",""+objTopic.getJSONArray("capsules"));
2222
 
2223
                    for (j = 0; j < arrayCapsules.length(); j++) {
2224
                        objCapsule = arrayCapsules.getJSONObject(j);
2225
                        uuid = objCapsule.getString("uuid");
2226
                        capsule = capsuleDao.selectByUuid(uuid);
2227
                        if(capsule == null) {
2228
                            capsule = new Capsule();
2229
                            capsule.setTopicUuid(topic.getUuid());
2230
                            capsule.setUuid(uuid);
2231
                            capsule.setName(objCapsule.getString("name"));
2232
                            capsule.setDescription(objCapsule.getString("description"));
2233
                            capsule.setImage(objCapsule.getString("image"));
2234
                            capsule.setPosition(objCapsule.getInt("position"));
2235
                            capsule.setAddedOn(objCapsule.getString("added_on"));
2236
                            capsule.setUpdatedOn(objCapsule.getString("updated_on"));
2237
                           // Log.e("Capsula ","added on"+objCapsule.getString("added_on"));
2238
                            capsuleDao.insert(capsule);
2239
                        } else {
2240
                            capsule = new Capsule();
2241
                            capsule.setTopicUuid(topic.getUuid());
2242
                            capsule.setName(objCapsule.getString("name"));
2243
                            capsule.setDescription(objCapsule.getString("description"));
2244
                            capsule.setImage(objCapsule.getString("image"));
2245
                            capsule.setPosition(objCapsule.getInt("position"));
2246
                            capsule.setAddedOn(objCapsule.getString("added_on"));
2247
                            capsule.setUpdatedOn(objCapsule.getString("updated_on"));
2248
                           // Log.e("Capsula ","added on"+objCapsule.getString("added_on"));
2249
                            capsuleDao.update(capsule);
2250
                        }
2251
 
2252
 
2253
 
2254
 
2255
                        arraySlides = objCapsule.getJSONArray("slides");
2256
                        for (x = 0; x < arraySlides.length(); x++) {
2257
                            objSlide = arraySlides.getJSONObject(x);
2258
 
2259
 
2260
                            uuid = objSlide.getString("uuid");
2261
                            slide = slideDao.selectByUuid(uuid);
2262
 
2263
                            if(slide == null) {
2264
 
2265
                                slide = new Slide();
2266
                                slide.setUuid(uuid);
2267
                                slide.setTopicUuid(capsule.getTopicUuid());
2268
                                slide.setCapsuleUuid(capsule.getUuid());
2269
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2270
                                slide.setName(objSlide.getString("name"));
2271
                                slide.setDescription(objSlide.getString("description"));
2272
                                slide.setPosition(objSlide.getInt("position"));
2273
                                slide.setType(objSlide.getString("type"));
2274
                                slide.setFile(objSlide.getString("file"));
2275
                                slide.setBackground(objSlide.getString("background"));
2276
 
2277
                                slideDao.insert(slide);
2278
                            } else {
2279
                                slide.setTopicUuid(capsule.getTopicUuid());
2280
                                slide.setCapsuleUuid(capsule.getUuid());
2281
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2282
                                slide.setName(objSlide.getString("name"));
2283
                                slide.setDescription(objSlide.getString("description"));
2284
                                slide.setPosition(objSlide.getInt("position"));
2285
                                slide.setType(objSlide.getString("type"));
2286
                                slide.setFile(objSlide.getString("file"));
2287
                                slide.setBackground(objSlide.getString("background"));
2288
 
2289
                                slideDao.update(slide);
2290
                            }
2291
                        }
2292
 
2293
                    }
2294
 
2295
 
2296
                }
2297
            }
2298
 
2299
            if(data.has( "extended")) {
2300
 
2301
                JSONObject objExtended;
2302
                JSONObject objItem;
2303
                JSONArray objItems;
2304
 
2305
 
2306
 
2307
                UserExtended userExtended;
2308
 
2309
                JSONArray extendedCompanies = data.getJSONArray("extended");
2310
                for(i = 0 ; i < extendedCompanies.length(); i++)
2311
                {
2312
                    objExtended = extendedCompanies.getJSONObject(i);
2313
                    if(objExtended.has("details")) {
2314
                        uuid = objExtended.getString("company_uuid");
2315
 
2316
 
2317
                        company = companyDao.selectByUuid(uuid);
2318
                        if (company == null) {
2319
                            company = new Company();
2320
                            company.setUuid(objExtended.getString("company_uuid"));
2321
                            company.setName(objExtended.getString("company_name"));
2322
                            company.setImage(objExtended.getString("company_image"));
2323
 
2324
                            companyDao.insert(company);
2325
                        } else {
2326
                            company.setName(objExtended.getString("company_name"));
2327
                            company.setImage(objExtended.getString("company_image"));
2328
 
2329
                            companyDao.update(company);
2330
                        }
2331
 
2332
                        objItems = objExtended.getJSONArray("details");
2333
                        for(j = 0 ; j < objItems.length(); j++) {
2334
                            objItem = objItems.getJSONObject(j);
2335
 
2336
                            uuid =  objItem.getString("uuid");
2337
 
2338
                            userExtended = userExtendedDao.selectByUuid(uuid);
2339
                            if(userExtended == null) {
2340
                                userExtended = new UserExtended();
2341
                                userExtended.setCompanyUuid(company.getUuid());
2342
                                userExtended.setUuid(uuid);
2343
                                userExtended.setLabel(objItem.getString("label"));
2344
                                userExtended.setValue(objItem.getString("value"));
2345
                                userExtendedDao.insert(userExtended);
2346
                            } else {
2347
                                userExtended.setCompanyUuid(company.getUuid());
2348
                                userExtended.setLabel(objItem.getString("label"));
2349
                                userExtended.setValue(objItem.getString("value"));
2350
                                userExtendedDao.update(userExtended);
2351
                            }
2352
 
2353
 
2354
 
2355
 
2356
                        }
2357
                    }
2358
                }
2359
 
2360
            }
2361
 
2362
 
2363
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2364
            if(data.has("max_date_changes")) {
2365
                String max_date_changes = data.getString("max_date_changes");
2366
                Log.d("syncFromServer", "max_date_changes : " + max_date_changes);
2367
 
2368
                if(!TextUtils.isEmpty(max_date_changes)) {
2369
                    preference.setMaxDateChanges(max_date_changes);
2370
                }
2371
            } else {
2372
                Log.d("syncFromServer", "No max_date_changes");
2373
            }
2374
 
2375
            Calendar calendar = Calendar.getInstance();
2376
            Date date = calendar.getTime();
2377
 
2378
            String  addedOn = simpleDateFormat.format(date);
2379
 
2380
            List<Company> companies = mAppDatabase.getCompanyDao().selectAll();
2381
            int companySize = companies.size();
2382
 
2383
            if(companySize > 0) {
2384
 
2385
                if(TextUtils.isEmpty(preference.getCompanyUuidActive())) {
2386
 
2387
                    preference.setCompanyUuidActive(companies.get(0).getUuid());
2388
 
2389
                } else {
2390
 
2391
                    boolean companyExist = false;
2392
                    for(i = 0; i < companies.size(); i++) {
2393
 
2394
                        if (companies.get(i).getUuid().equals(preference.getCompanyUuidActive())) {
2395
                            companyExist = true;
2396
                            break;
2397
                        }
2398
                    }
2399
 
2400
                    if(!companyExist && companies.size() > 0) {
2401
                        preference.setCompanyUuidActive(companies.get(0).getUuid());
2402
                    }
2403
                }
2404
 
2405
            } else {
2406
                preference.setCompanyUuidActive("");
2407
            }
2408
 
2409
 
2410
 
2411
            preference.setLastDataRefresh(addedOn);
2412
            preference.setCompanyCount(companySize);
2413
            preference.save();
2414
 
2415
        } catch (JSONException e) {
2416
            Log.d(TAG, e.getMessage());
2417
        }
2418
    }
2419
 
2420
    @Override
2421
    public void requestExecuteSyncAdapter() {
2422
            // Pass the settings flags by inserting them in a bundle
2423
            Bundle settingsBundle = new Bundle();
2424
            settingsBundle.putBoolean(
2425
                    ContentResolver.SYNC_EXTRAS_MANUAL, true);
2426
            settingsBundle.putBoolean(
2427
                    ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
2428
 
2429
            ContentResolver.requestSync(mAccount, Constants.AUTHORITY, settingsBundle);
2430
    }
2431
 
2432
 
2433
    private void processResponseServerChanges(String dataString)
2434
    {
2435
 
2436
        Log.d(TAG, "processResponseServerChanges = " + dataString);
2437
 
2438
        try {
2439
            JSONObject objJSON = new JSONObject(dataString);
2440
            boolean success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2441
 
2442
 
2443
            if(success) {
2444
                Calendar calendar = Calendar.getInstance();
2445
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2446
                preference.setLastDataRefresh(simpleDateFormat.format(calendar.getTime()));
2447
                preference.save();
2448
 
2449
                String max_date_changes = "";
2450
                boolean processChanges = false;
2451
 
2452
                JSONObject data = objJSON.getJSONObject("data");
2453
 
2454
 
2455
                if(data.has("max_date_changes") && data.has("new_capsules")) {
2456
                    int new_capsules = data.getInt("new_capsules");
2457
                    max_date_changes = data.getString("max_date_changes");
2458
 
2459
 
2460
 
2461
 
2462
                    processChanges = new_capsules > 0 && !max_date_changes.equals(preference.getMaxDateChanges());
2463
                } else {
2464
                    processChanges = false;
2465
                }
2466
 
2467
                if(processChanges && !max_date_changes.isEmpty()) {
2468
                    int new_capsules = data.getInt("new_capsules");
2469
                    String message = new_capsules == 1
2470
                            ? "Hay 1 cápsula disponible"
2471
                            : "Hay " + new_capsules + " cápsulas disponible";
2472
 
2473
 
2474
 
2475
 
2476
                    showMessageSnackBarWithClose(message);
2477
 
2478
 
2479
                    preference.setMaxDateChanges(max_date_changes);
2480
 
2481
                    if(!isForeground) {
2482
                        String body = new_capsules == 1
2483
                                ? "Hay 1 cápsula disponible"
2484
                                : "Hay " + new_capsules + " cápsulas disponible";
2485
                        showFcmNotification("Nuevo contenido", body, new_capsules, "", false);
2486
                    }
2487
 
2488
                    /*
2489
                    if(!isForeground) {
2490
                        String body = new_capsules == 1
2491
                                ? "Hay 1 cápsula nueva disponible"
2492
                                : "Hay " + new_capsules + " cápsulas disponible";
2493
                        showFcmNotification("Nuevo contenido", body, new_capsules);
2494
 
2495
 
2496
                        AnswerDao answerDao = mAppDatabase.getAnswerDao();
2497
                        answerDao.removeAll();
2498
 
2499
                        QuestionDao questionDao = mAppDatabase.getQuestionDao();
2500
                        questionDao.removeAll();
2501
 
2502
                        QuizDao quizDao = mAppDatabase.getQuizDao();
2503
                        quizDao.removeAll();
2504
 
2505
                        SlideDao slideDao = mAppDatabase.getSlideDao();
2506
                        slideDao.removeAll();
2507
 
2508
                        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
2509
                        capsuleDao.removeAll();
2510
 
2511
                        TopicDao topicDao = mAppDatabase.getTopicDao();
2512
                        topicDao.removeAll();
2513
 
2514
                        CompanyDao companyDao = mAppDatabase.getCompanyDao();
2515
                        companyDao.removeAll();
2516
 
2517
                        UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
2518
                        userExtendedDao.removeAll();
2519
 
2520
 
2521
                        this.syncFromServer(data);
2522
 
2523
 
2524
                        if(!TextUtils.isEmpty(preference.getSlideUuidActive())) {
2525
 
2526
                            Slide slide = mAppDatabase.getSlideDao().selectByUuid(preference.getSlideUuidActive());
2527
                            if(slide == null) {
2528
                                preference.setFragmentIdxActive(Constants.IDX_FRAGMENT_TOPICS);
2529
                                preference.save(this);
2530
                            }
2531
 
2532
                        }
2533
                    }*/
2534
 
2535
 
2536
                }
2537
            }
2538
        } catch (JSONException e) {
2539
            Log.d(TAG, e.getMessage());
2540
        }
2541
    }
2542
 
2543
    @Override
2544
    public AppDatabase getDatabase() {
2545
        return mAppDatabase;
2546
    }
2547
 
2548
    @Override
2549
    public void syncToServerOrCheckChanges()
2550
    {
2551
        if(TextUtils.isEmpty(preference.getDeviceUuid())) {
2552
            return;
2553
        }
2554
 
2555
        SyncDao syncDao = mAppDatabase.getSyncDao();
2556
        List<Sync> records = syncDao.selectBatch();
2557
 
2558
        if(records.size() > 0) {
2559
            syncToServer(records);
2560
        } else {
2561
 
2562
                long timeLast = 0;
2563
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2564
                if (!TextUtils.isEmpty(preference.getLastDataRefresh())) {
2565
                    try {
2566
                        timeLast = simpleDateFormat.parse(preference.getLastDataRefresh()).getTime();
2567
                    } catch (Exception e) {
2568
 
2569
                    }
2570
 
2571
                }
2572
 
2573
 
2574
                Calendar calendar = Calendar.getInstance();
2575
                long timeNow = calendar.getTime().getTime();
2576
 
2577
                if(timeNow > (timeLast + Constants.CHECK_CHANGES_TOKEN_INTERVAL)){
2578
 
2579
                    //Procesamiento en caso que el token no este, check cada 15 minutos.
2580
 
2581
                    if(preference.isRefreshTokenIsRequired()) {
2582
                        FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
2583
                            @Override
2584
                            public void onComplete(@NonNull Task<String> task) {
2585
                                if (!task.isSuccessful()) {
2586
                                    Log.w(TAG, "Fetching FCM registration token failed", task.getException());
2587
                                    return;
2588
                                }
2589
 
2590
                                // Get new FCM registration token
2591
                                String token = task.getResult();
2592
 
2593
                                Log.e("BUG Token", "Token 3 :  " + token);
2594
 
2595
                                createSyncRecordNewToken(token);
2596
 
2597
                                preference.setRefreshTokenIsRequired(false);
2598
                                preference.save();
2599
                            }
2600
                        });
2601
 
2602
 
2603
                    } else {
2604
 
2605
                        if (preference.getDeviceToken().isEmpty()) {
2606
                            FirebaseMessaging.getInstance().deleteToken().addOnCompleteListener(new OnCompleteListener<Void>() {
2607
                                @Override
2608
                                public void onComplete(@NonNull Task<Void> task) {
2609
                                    preference.setRefreshTokenIsRequired(true);
2610
                                    preference.save();
2611
 
2612
                                    Log.e("Esta vacio"," mando delete token");
2613
 
2614
                                }
2615
                            });
2616
                        }
2617
                    }
2618
                }
2619
 
2620
                 if (timeNow > (timeLast + Constants.CHECK_CHANGES_INTERVAL)) {
2621
                     //Solicitar revision de cambios cada 4 horas.
2622
                    requestCheckChanges();
2623
                }
2624
        }
2625
    }
2626
 
2627
 
2628
 
2629
    public void syncToServer(List<Sync> records)
2630
    {
2631
 
2632
 
2633
        int maxRecordsSyncBatch = 0;
2634
        FormBody.Builder formBodyBatchBuilder = new FormBody.Builder();
2635
        formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_DEVICE_UUID, preference.getDeviceUuid());
2636
 
2637
        for(Sync record : records)
2638
        {
2639
 
2640
           // Log.e("Ingreso a", "syncToServer"+record.getType()+" data"+record.getData());
2641
 
2642
          //  Log.d(TAG, "SyncRecord ID = " + record.getId() + " Data : "  + record.getData() + " Type= " + record.getType());
2643
 
2644
 
2645
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {
2646
                Log.d(TAG, "Device");
2647
 
2648
 
2649
                try {
2650
                    Http http = new Http(this.getCacheDir());
2651
                    OkHttpClient client = http.getHttpClient(false);
2652
 
2653
                    RequestBody formBody = new FormBody.Builder()
2654
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID,  String.valueOf(Configuration.APPLICATION_ID))
2655
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
2656
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
2657
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
7 gabriel 2658
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE  + " " + Build.VERSION_CODES.class.getFields()[Build.VERSION.SDK_INT].getName())
1 gabriel 2659
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
2660
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
2661
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
2662
                            .build();
2663
 
2664
                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
2665
                    Request request = new Request.Builder()
2666
                            .url(Configuration.URL_DEVICE)
2667
                            .post(formBody)
2668
                            .build();
2669
 
2670
                    isSyncDevice = true;
2671
 
2672
                    Call call = client.newCall(request);
7 gabriel 2673
                    call.enqueue(new Callback() {
1 gabriel 2674
                        public void onResponse(Call call, Response response)
2675
                                throws IOException {
2676
                            Log.d(TAG, "Response Device :  " +  response.body().toString());
2677
                            isSyncDevice = false;
2678
 
2679
                            processResponseSyncToServer(response.body().string(),"device");
2680
                        }
2681
 
2682
                        public void onFailure(Call call, IOException e) {
2683
                            isSyncDevice = false;
2684
                            Log.d(TAG, "Error :  " +  e.getMessage());
2685
                        }
2686
                    });
2687
                } catch (Exception e) {
2688
                }
2689
            }
2690
 
2691
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken && !isSyncDevice) {
2692
                isSyncToken = true;
2693
                Log.d(TAG, "FCM");
2694
                Log.e("Token a Sync",""+record.getData());
2695
 
2696
                try {
2697
                    Http http = new Http(this.getCacheDir());
2698
                    OkHttpClient client = http.getHttpClient(false);
2699
 
2700
                    RequestBody formBody = new FormBody.Builder()
2701
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID,preference.getDeviceUuid())
2702
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
2703
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
2704
                            .build();
2705
 
2706
                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
2707
                    Request request = new Request.Builder()
2708
                            .url(Configuration.URL_FCM)
2709
                            .post(formBody)
2710
                            .build();
2711
 
2712
                    Call call = client.newCall(request);
7 gabriel 2713
                    call.enqueue(new Callback() {
1 gabriel 2714
                        public void onResponse(Call call, Response response)
2715
                                throws IOException {
2716
                            isSyncToken = false;
2717
                            Log.e("Se envio", "Procesando respuesta");
2718
                            processResponseSyncToServer(response.body().string(),"");
2719
                        }
2720
 
2721
                        public void onFailure(Call call, IOException e) {
2722
                            Log.d(TAG, "Error :  " +  e.getMessage());
2723
                            isSyncToken = false;
2724
                        }
2725
                    });
2726
                } catch (Exception e) {
2727
 
2728
 
2729
                }
2730
            }
2731
 
2732
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_SYNC ) {
2733
                Log.d(TAG, "SYNC BATCH");
2734
                maxRecordsSyncBatch++;
2735
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_DATA + maxRecordsSyncBatch, record.getData());
2736
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_SYNC_ID + maxRecordsSyncBatch, String.valueOf(record.getId()));
2737
            }
2738
        }
2739
 
2740
 
2741
        if(maxRecordsSyncBatch > 0 && !isSyncBatch) {
2742
            Log.d(TAG, "Sync Batch");
2743
            isSyncBatch = true;
2744
 
2745
            try {
2746
                Http http = new Http(this.getCacheDir());
2747
                OkHttpClient client = http.getHttpClient(false);
2748
 
2749
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_MAX_RECORDS, String.valueOf(maxRecordsSyncBatch));
2750
                RequestBody formBody = formBodyBatchBuilder.build();
2751
 
2752
                Log.d(TAG, "URL = " + Configuration.URL_SYNC_BATCH);
2753
                Request request = new Request.Builder()
2754
                    .url(Configuration.URL_SYNC_BATCH)
2755
                    .post(formBody)
2756
                    .build();
2757
 
2758
                Call call = client.newCall(request);
7 gabriel 2759
                call.enqueue(new Callback() {
1 gabriel 2760
                    public void onResponse(Call call, Response response) throws IOException {
2761
                        isSyncBatch = false;
2762
                        processResponseServerBatch(response.body().string());
2763
                    }
2764
 
2765
                    public void onFailure(Call call, IOException e) {
2766
                        Log.d(TAG, "Error :  " +  e.getMessage());
2767
                        isSyncBatch = false;
2768
                    }
2769
                });
2770
            } catch (Exception e) {
2771
 
2772
 
2773
            }
2774
        }
2775
 
2776
 
2777
    }
2778
 
2779
    private void processResponseServerBatch(String dataString)
2780
    {
2781
        boolean success = false;
2782
        long sync_id = 0;
2783
 
2784
        Log.d(TAG, "processResponseServer = " + dataString);
2785
        try {
2786
            JSONObject objJSON = new JSONObject(dataString);
2787
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2788
            if(success  && objJSON.has("data")) {
2789
                JSONArray jsonArrayData = objJSON.getJSONArray("data");
2790
 
2791
 
2792
                JSONObject jsonObjectData;
2793
                int max = jsonArrayData.length();
2794
                for(int i = 0; i < max; i++) {
2795
                    jsonObjectData = jsonArrayData.getJSONObject(i);
2796
 
2797
                    if(jsonObjectData.has("success") && jsonObjectData.getBoolean("success")) {
2798
                        sync_id = jsonObjectData.getLong("sync_id");
2799
 
2800
                        mAppDatabase.getSyncDao().remove(sync_id);
2801
 
2802
                    }
2803
 
2804
 
2805
                }
2806
 
2807
                /*
2808
                if(jsonObjectData.has("message")) {
2809
                    message = jsonObjectData.getString("message");
2810
                }
2811
 
2812
                if(jsonObjectData.has("aes")) {
2813
                    preference.setAes(jsonObjectData.getString("aes"));
2814
                    preference.save(this);
2815
                }
2816
 
2817
                if(jsonObjectData.has("password")) {
2818
                    preference.setPassword(jsonObjectData.getString("password"));
2819
                    preference.save(this);
2820
                }
2821
                */
2822
            }
2823
            if(success && sync_id > 0) {
2824
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2825
                mAppDatabase.getSyncDao().remove(sync_id);
2826
 
2827
            }
2828
        } catch (JSONException e) {
2829
            e.printStackTrace();
2830
        }
2831
    }
2832
 
2833
    private void processResponseSyncToServer(String dataString, String origen)
2834
    {
2835
        boolean success = false;
2836
        long sync_id = 0;
2837
 
2838
        Log.d(TAG, "processResponseServer = " + dataString);
2839
        try {
2840
            JSONObject objJSON = new JSONObject(dataString);
2841
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2842
            if(success  && objJSON.has("data")) {
2843
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
2844
 
2845
 
2846
                if(jsonObjectData.has("sync_id")) {
2847
                    sync_id = jsonObjectData.getLong("sync_id");
2848
                }
2849
 
2850
                /*
2851
                if(jsonObjectData.has("message")) {
2852
                    message = jsonObjectData.getString("message");
2853
                }
2854
 
2855
                if(jsonObjectData.has("aes")) {
2856
                    preference.setAes(jsonObjectData.getString("aes"));
2857
                    preference.save(this);
2858
                }
2859
 
2860
                if(jsonObjectData.has("password")) {
2861
                    preference.setPassword(jsonObjectData.getString("password"));
2862
                    preference.save(this);
2863
                }
2864
                */
2865
            }
2866
            Log.d(TAG, "SyncID = " + sync_id);
2867
            if(success && sync_id > 0) {
2868
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2869
                mAppDatabase.getSyncDao().remove(sync_id);
2870
 
2871
                if(origen.equals("device"))
2872
                {
2873
                    syncToServerOrCheckChanges();
2874
 
2875
                }
2876
            }
2877
        } catch (JSONException e) {
2878
            e.printStackTrace();
2879
        }
2880
    }
2881
 
2882
    /*
2883
    private void processResponseSyncTokenFCMtoServer(String dataString)
2884
    {
2885
        Log.e("Respuesta",""+dataString);
2886
        boolean success = false;
2887
 
2888
        try {
2889
            JSONObject objJSON = new JSONObject(dataString);
2890
            success = objJSON.has("success") && objJSON.getBoolean("success");
2891
 
2892
            if(success) {
2893
                Log.e("Token almacenado"," en server de manera exitosa");
2894
            }
2895
        } catch (JSONException e) {
2896
            e.printStackTrace();
2897
        }
2898
    }
2899
 
2900
 
2901
     */
2902
 
2903
 
2904
    /*
2905
    private void processResponseServerCheckChanges(String dataString) {
2906
 
2907
        Log.d(TAG, "processResponseServerCheckChanges = " + dataString);
2908
 
2909
        runOnUiThread(new Runnable() {
2910
 
2911
            @Override
2912
            public void run() {
2913
 
2914
                try {
2915
                    JSONObject objJSON = new JSONObject(dataString);
2916
                    boolean success = objJSON.has("success") ? objJSON.getBoolean("success") : false;
2917
                    String message = "";
2918
                    if (objJSON.has("data")) {
2919
                        Object item = objJSON.get("data");
2920
                        if (item instanceof String) {
2921
                            message = item.toString();
2922
                        }
2923
                    }
2924
 
2925
                    if (success) {
2926
                        mAppDatabase.getAnswerDao().removeAll();
2927
                        mAppDatabase.getQuestionDao().removeAll();
2928
                        mAppDatabase.getQuizDao().removeAll();
2929
                        mAppDatabase.getSlideDao().removeAll();
2930
                        mAppDatabase.getCapsuleDao().removeAll();
2931
                        mAppDatabase.getTopicDao().removeAll();
2932
 
2933
 
2934
                        JSONObject data = objJSON.getJSONObject("data");
2935
                        syncFromServer(data);
2936
 
2937
 
2938
                    }
2939
 
2940
 
2941
                } catch (JSONException e) {
2942
                    Log.d(TAG, e.getMessage());
2943
                }
2944
 
2945
                reloadNavHeader();
2946
 
2947
 
2948
            }
2949
        });
2950
    }
2951
     */
2952
 
2953
 
2954
}