Proyectos de Subversion Android Microlearning - Inconcert

Rev

Rev 18 | | Comparar con el anterior | Ultima modificación | Ver Log |

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