Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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