Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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