Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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