Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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