Proyectos de Subversion Android Microlearning

Rev

Rev 4 | Ir a la última revisión | | Ultima modificación | Ver Log |

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