Proyectos de Subversion Android Microlearning - Inconcert

Rev

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