Proyectos de Subversion Android Microlearning - Inconcert

Rev

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

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