Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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