Proyectos de Subversion Android Microlearning - Inconcert

Rev

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