Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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