Proyectos de Subversion Android Microlearning - Inconcert

Rev

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