Proyectos de Subversion Android Microlearning - Inconcert

Rev

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