Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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