Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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