Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 49 | Rev 52 | 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 {
49 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
 
49 gabriel 843
                        Toast.makeText(MainActivity.this,"Actualizando tu contenido...",Toast.LENGTH_LONG).show();
50 gabriel 844
                        invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
49 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
 
49 gabriel 1747
    public void refreshContent(){
1 gabriel 1748
 
49 gabriel 1749
        try {
1750
            TimeZone timeZone = TimeZone.getTimeZone("UTC");
1751
            Calendar calendar = Calendar.getInstance(timeZone);
1752
            TimeZone tz = calendar.getTimeZone();
1753
            int created = (int) (calendar.getTimeInMillis() / 1000);
1754
 
1755
            Random random = new Random(created);
1756
            int rand = 1000 + random.nextInt(8999);
1757
 
1758
 
1759
            Log.d(TAG, "token = " + preference.getDeviceUuid());
1760
            Log.d(TAG, "created = " + created);
1761
            Log.d(TAG, "rand = " + rand);
1762
            Log.d(TAG, "calc = " + preference.getPassword() + ':' + created + ':' + rand);
1763
 
1764
            String secret = MD5.generar(preference.getPassword() + ':' + created + ':' + rand);
1765
 
1766
            Log.d(TAG, "secret = " + secret);
1767
 
1768
            Log.d(TAG, "URL = " + Configuration.URL_REFRESH);
1769
            Request request = new Request.Builder()
1770
                    .url(Configuration.URL_REFRESH)
1771
                    .build();
1772
 
1773
            Http http = new Http(getCacheDir(), preference.getDeviceUuid(), secret, created, rand);
1774
            OkHttpClient client = http.getHttpClient(false);
1775
 
1776
            Call call = client.newCall(request);
1777
            call.enqueue(new Callback() {
1778
                public void onResponse(Call call, Response response)
1779
                        throws IOException {
1780
                    processResponseServer(response.body().string());
1781
 
1782
                }
1783
 
1784
                public void onFailure(Call call, IOException e) {
1785
                    Log.d(TAG, "Error :  " + e.getMessage());
1786
                }
1787
            });
1788
 
1789
        } catch (Exception e) {
1790
           showMessageSnackBar(e.getMessage());
1791
        }
1792
    }
1793
 
1 gabriel 1794
    public void requestCheckChanges()
1795
    {
1796
        Log.d(TAG, "requestCheckChanges");
1797
        try {
1798
 
1799
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1800
            List<Capsule> capsules = capsuleDao.selectAll();
1801
 
1802
            if(capsules.size() > 0) {
1803
                //ArrayList<String> ids = new ArrayList<>();
1804
 
1805
                TimeZone timeZone = TimeZone.getTimeZone("UTC");
1806
                Calendar calendar = Calendar.getInstance(timeZone);
1807
                TimeZone tz = calendar.getTimeZone();
1808
                int created =  (int) (calendar.getTimeInMillis() / 1000);
1809
 
1810
                Random random = new Random(created);
1811
                int rand = 1000 + random.nextInt(8999);
1812
 
1813
 
1814
                //Log.d("requestCheckChanges", "token = " + preference.getDeviceUuid());
1815
                //Log.d("requestCheckChanges", "created = " + created);
1816
               // Log.d("requestCheckChanges", "rand = " + rand);
1817
                //Log.d("requestCheckChanges", "calc = " + preference.password + ':' +  created + ':' + rand);
1818
 
1819
                String secret = MD5.generar(preference.getPassword() + ':' +  created + ':' + rand);
1820
 
1821
                //Log.d("requestCheckChanges", "secret = " + secret);
1822
 
1823
 
1824
                FormBody.Builder formBodyCheckChangeBuilder = new FormBody.Builder();
1825
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_DEVICE_UUID, preference.getDeviceUuid());
1826
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_DATE_CHANGES, preference.getMaxDateChanges());
1827
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_IS_FOREGROUND, String.valueOf(isForeground ? 1 : 0));
1828
                Http http = new Http(this.getCacheDir(), preference.getDeviceUuid(), secret, created, rand);
1829
                OkHttpClient client = http.getHttpClient(false);
1830
 
1831
 
1832
 
1833
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(capsules.size()));
1834
                //formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(0));
1835
 
1836
              int i = 1;
1837
                for(Capsule capsule : capsules)
1838
                {
1839
                    Log.d("requestCheckChanges", "id" + i + " = " + capsule.getTopicUuid() + "|" + capsule.getUuid());
1840
 
1841
 
1842
                    formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_ID + i, capsule.getTopicUuid() + "|" + capsule.getUuid());
1843
                    i++;
1844
                }
1845
 
1846
 
1847
 
1848
                RequestBody formBody = formBodyCheckChangeBuilder.build();
1849
 
1850
                Log.d(TAG, "URL = " + Configuration.URL_CHECK_CHANGES);
1851
                Request request = new Request.Builder()
1852
                        .url(Configuration.URL_CHECK_CHANGES)
1853
                        .post(formBody)
1854
                        .build();
1855
 
1856
                Call call = client.newCall(request);
1857
                call.enqueue(new okhttp3.Callback() {
1858
                    public void onResponse(Call call, Response response)
1859
                            throws IOException {
1860
 
1861
 
1862
 
1863
                        processResponseServerChanges(response.body().string());
1864
                    }
1865
 
1866
                    public void onFailure(Call call, IOException e) {
1867
                        Log.d(TAG, "Error :  " +  e.getMessage());
1868
                    }
1869
                });
1870
            }
1871
 
1872
 
1873
 
1874
        } catch(Exception e) {
1875
 
1876
        }
1877
    }
1878
 
1879
 
1880
    public void syncFromServer(JSONObject data)
1881
    {
1882
        try {
1883
            JSONObject objUser = data.getJSONObject("user");
1884
            String userUuid = objUser.getString("uuid");
1885
 
1886
 
1887
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1888
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1889
            QuizDao quizDao = mAppDatabase.getQuizDao();
1890
            SlideDao slideDao = mAppDatabase.getSlideDao();
1891
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1892
            TopicDao topicDao = mAppDatabase.getTopicDao();
1893
            CompanyDao companyDao = mAppDatabase.getCompanyDao();
1894
            UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
1895
 
1896
 
1897
 
1898
            ProgressDao progressDao = mAppDatabase.getProgressDao();
1899
            progressDao.removeAllUserUuidNotEqual(userUuid);
1900
 
1901
 
1902
            UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1903
            userLogDao.removeAllUserUuidNotEqual(userUuid);
1904
 
1905
            JSONArray arrayCapsules;
1906
            JSONArray arraySlides;
1907
            JSONArray arrayAnswers;
1908
            JSONArray arrayQuestions;
1909
            JSONArray arrayProgress;
1910
            JSONArray arrayQuizzes;
1911
            JSONArray arrayUserLog;
1912
 
1913
            JSONObject objTopic;
1914
            JSONObject objCapsule;
1915
            JSONObject objSlide;
1916
            JSONObject objAnswer;
1917
            JSONObject objQuestion;
1918
            JSONObject objQuiz;
1919
            JSONObject objProgress;
1920
            JSONObject objUserLog;
1921
            int i,j,x;
1922
 
1923
            if(data.has("progress")) {
1924
 
1925
                arrayProgress = data.getJSONArray("progress");
1926
                for (i = 0; i < arrayProgress.length(); i++) {
1927
                    objProgress = arrayProgress.getJSONObject(i);
1928
 
1929
 
1930
                    Progress progress = null;
1931
 
1932
 
1933
                    userUuid = objProgress.getString("user_uuid");
1934
                    String type = objProgress.getString("type");
1935
                    String topicUuid = objProgress.getString("topic_uuid");
1936
                    String capsuleUuid = objProgress.getString("capsule_uuid");
1937
                    String slideUuid = objProgress.getString("slide_uuid");
1938
 
1939
                    if(type == Constants.PROGERSS_TYPE_SLIDE) {
1940
                        progress = progressDao.selectBySlideUuidAndUserUuid(slideUuid, userUuid);
1941
                    } else if(type == Constants.PROGERSS_TYPE_CAPSULE) {
1942
                        progress = progressDao.selectByCapsuleUuidAndUserUuid(capsuleUuid, userUuid);
1943
                    } else if(type == Constants.PROGERSS_TYPE_TOPIC) {
1944
                        progress = progressDao.selectByTopicUuidAndUserUuid(topicUuid, userUuid);
1945
                    }
1946
 
1947
 
1948
                    if(progress == null) {
1949
                        progress = new Progress();
1950
                        progress.setUserUuid(userUuid);
1951
                        progress.setCompanyUuid(objProgress.getString("company_uuid"));
1952
                        progress.setTopicUuid(topicUuid);
1953
                        progress.setCapsuleUuid(capsuleUuid);
1954
                        progress.setSlideUuid(slideUuid);
1955
                        progress.setProgress(objProgress.getDouble("progress"));
1956
                        progress.setTotalSlides(objProgress.getInt("total_slides"));
1957
                        progress.setViewSlides(objProgress.getInt("view_slides"));
1958
                        progress.setType(type);
1959
                        progress.setReturning(objProgress.getInt("returning"));
1960
                        progress.setReturningAfterCompleted(objProgress.getInt("returning_after_completed"));
1961
                        progress.setCompleted(objProgress.getInt("completed"));
1962
                        progress.setAddedOn(objProgress.getString("added_on"));
1963
                        progress.setUpdatedOn(objProgress.getString("updated_on"));
1964
 
1965
                        progressDao.insert(progress);
1966
                    }
1967
 
1968
 
1969
                }
1970
            }
1971
 
1972
            if(data.has("userlog")) {
1973
                arrayUserLog = data.getJSONArray("userlog");
1974
                for (i = 0; i < arrayUserLog.length(); i++) {
1975
                    objUserLog = arrayUserLog.getJSONObject(i);
1976
 
1977
                    userUuid = objUserLog.getString("user_uuid");
1978
                    String activity = objUserLog.getString("activity");
1979
                    String added_on = objUserLog.getString("added_on");
1980
 
1981
                    UserLog userLog = userLogDao.selectOneByUserUuidAndActivityAndAddedOn(userUuid, activity, added_on);
1982
                    if(userLog == null) {
1983
                        userLog = new UserLog();
1984
                        userLog.setUserUuid(objUserLog.getString("user_uuid"));
1985
                        userLog.setCompanyUuid(objUserLog.getString("company_uuid"));
1986
                        userLog.setTopicUuid(objUserLog.getString("topic_uuid"));
1987
                        userLog.setCapsuleUuid(objUserLog.getString("capsule_uuid"));
1988
                        userLog.setSlideUuid(objUserLog.getString("slide_uuid"));
1989
                        userLog.setActivity(objUserLog.getString("activity"));
1990
                        userLog.setAddedOn(objUserLog.getString("added_on"));
1991
                        userLogDao.insert(userLog);
1992
                    }
1993
                }
1994
            }
1995
 
19 gabriel 1996
            String uuid;
1997
            Company company;
1 gabriel 1998
            if(data.has("quizzes")) {
19 gabriel 1999
                Quiz quiz;
2000
                Question question;
2001
                Answer answer;
2002
 
1 gabriel 2003
                arrayQuizzes = data.getJSONArray("quizzes");
2004
                for (i = 0; i < arrayQuizzes.length(); i++) {
2005
                    objQuiz = arrayQuizzes.getJSONObject(i);
19 gabriel 2006
                    uuid = objQuiz.getString("company_uuid");
2007
                    company = companyDao.selectByUuid(uuid);
1 gabriel 2008
                    if (company == null) {
2009
                        company = new Company();
2010
                        company.setUuid(objQuiz.getString("company_uuid"));
2011
                        company.setName(objQuiz.getString("company_name"));
2012
                        company.setImage(objQuiz.getString("company_image"));
2013
 
2014
                        companyDao.insert(company);
19 gabriel 2015
                    } else {
2016
                        company.setName(objQuiz.getString("company_name"));
2017
                        company.setImage(objQuiz.getString("company_image"));
2018
 
2019
                        companyDao.update(company);
1 gabriel 2020
                    }
2021
 
19 gabriel 2022
                    uuid =  objQuiz.getString("uuid");
2023
                    quiz = quizDao.selectByUuid(uuid);
1 gabriel 2024
 
19 gabriel 2025
                    if(quiz == null) {
2026
                        quiz = new Quiz();
2027
                        quiz.setUuid(  objQuiz.getString("uuid"));
2028
                        quiz.setCompanyUuid(  company.getUuid() );
2029
                        quiz.setFailed(  objQuiz.getString("failed"));
2030
                        quiz.setName(  objQuiz.getString("name"));
2031
                        quiz.setText(  objQuiz.getString("text"));
2032
                        quiz.setPoints(  objQuiz.getInt("points"));
2033
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2034
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2035
                        quizDao.insert(quiz);
2036
 
2037
                    } else {
2038
                        quiz.setCompanyUuid(  company.getUuid() );
2039
                        quiz.setFailed(  objQuiz.getString("failed"));
2040
                        quiz.setName(  objQuiz.getString("name"));
2041
                        quiz.setText(  objQuiz.getString("text"));
2042
                        quiz.setPoints(  objQuiz.getInt("points"));
2043
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2044
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2045
                        quizDao.update(quiz);
2046
                    }
2047
 
1 gabriel 2048
                    arrayQuestions = objQuiz.getJSONArray("questions");
2049
                    for (j = 0; j < arrayQuestions.length(); j++) {
2050
                        objQuestion = arrayQuestions.getJSONObject(j);
2051
 
19 gabriel 2052
                        uuid = objQuestion.getString("uuid");
2053
                        question = questionDao.selectByUuid(uuid);
2054
                        if(question == null) {
2055
                            question = new Question();
2056
                            question.setQuizUuid( quiz.getUuid());
2057
                            question.setUuid(uuid) ;
2058
                            question.setText( objQuestion.getString("text"));
2059
                            question.setType( objQuestion.getString("type"));
2060
                            question.setPoints( objQuestion.getInt("points"));
2061
                            question.setMaxlength( objQuestion.getInt("maxlength"));
1 gabriel 2062
 
19 gabriel 2063
                            questionDao.insert(question);
2064
                        } else {
2065
                            question.setQuizUuid( quiz.getUuid());
2066
                            question.setText( objQuestion.getString("text"));
2067
                            question.setType( objQuestion.getString("type"));
2068
                            question.setPoints( objQuestion.getInt("points"));
2069
                            question.setMaxlength( objQuestion.getInt("maxlength"));
2070
 
2071
                            questionDao.update(question);
2072
                        }
2073
 
2074
 
2075
 
2076
 
1 gabriel 2077
                        arrayAnswers = objQuestion.getJSONArray("answers");
2078
                        for (x = 0; x < arrayAnswers.length(); x++) {
2079
                            objAnswer = arrayAnswers.getJSONObject(x);
2080
 
19 gabriel 2081
                            uuid = objAnswer.getString("uuid");
2082
                            answer = answerDao.selectByUuid(uuid);
1 gabriel 2083
 
19 gabriel 2084
                            if(answer == null) {
1 gabriel 2085
 
19 gabriel 2086
                                answer = new Answer();
2087
                                answer.setQuestionUuid(question.getUuid());
2088
                                answer.setUuid(uuid);
2089
                                answer.setText(objAnswer.getString("text"));
2090
                                answer.setPoints(objAnswer.getInt("points"));
2091
                                answer.setCorrect(objAnswer.getString("correct"));
2092
 
2093
                                answerDao.insert(answer);
2094
                            } else {
2095
                                answer.setQuestionUuid(question.getUuid());
2096
                                answer.setText(objAnswer.getString("text"));
2097
                                answer.setPoints(objAnswer.getInt("points"));
2098
                                answer.setCorrect(objAnswer.getString("correct"));
2099
                                answerDao.update(answer);
2100
                            }
2101
                        }
1 gabriel 2102
                    }
2103
                }
2104
            }
2105
 
2106
 
2107
 
2108
 
2109
 
2110
            if(data.has("topics")) {
19 gabriel 2111
                Topic topic;
2112
                Capsule capsule;
2113
                Slide slide;
1 gabriel 2114
 
2115
                JSONArray arrayTopics = data.getJSONArray("topics");
2116
                for (i = 0; i < arrayTopics.length(); i++) {
2117
                    objTopic = arrayTopics.getJSONObject(i);
2118
 
19 gabriel 2119
                    uuid = objTopic.getString("company_uuid");
2120
                    company = companyDao.selectByUuid(uuid);
1 gabriel 2121
                    if (company == null) {
2122
                        company = new Company();
2123
                        company.setUuid(objTopic.getString("company_uuid"));
2124
                        company.setName(objTopic.getString("company_name"));
2125
                        company.setImage(objTopic.getString("company_image"));
2126
 
2127
                        companyDao.insert(company);
19 gabriel 2128
                    } else {
2129
                        company.setName(objTopic.getString("company_name"));
2130
                        company.setImage(objTopic.getString("company_image"));
2131
 
2132
                        companyDao.update(company);
1 gabriel 2133
                    }
2134
 
19 gabriel 2135
                    uuid = objTopic.getString("uuid");
2136
                    topic = topicDao.selectByUuid(uuid);
1 gabriel 2137
 
19 gabriel 2138
                    if (topic == null) {
2139
                        topic = new Topic();
2140
                        topic.setUuid(uuid);
2141
                        topic.setCompanyUuid(company.getUuid());
2142
                        topic.setName(objTopic.getString("name"));
2143
                        topic.setDescription(objTopic.getString("description"));
2144
                        topic.setImage(objTopic.getString("image"));
2145
                        topic.setPosition(objTopic.getInt("position"));
2146
                        topicDao.insert(topic);
2147
                    } else {
2148
                        topic.setCompanyUuid(company.getUuid());
2149
                        topic.setName(objTopic.getString("name"));
2150
                        topic.setDescription(objTopic.getString("description"));
2151
                        topic.setImage(objTopic.getString("image"));
2152
                        topic.setPosition(objTopic.getInt("position"));
2153
                        topicDao.update(topic);
2154
                    }
2155
 
2156
 
2157
 
2158
 
2159
 
1 gabriel 2160
                    arrayCapsules = objTopic.getJSONArray("capsules");
27 gabriel 2161
                  //  Log.e("Objeto:",""+objTopic.getJSONArray("capsules"));
21 gabriel 2162
 
1 gabriel 2163
                    for (j = 0; j < arrayCapsules.length(); j++) {
2164
                        objCapsule = arrayCapsules.getJSONObject(j);
19 gabriel 2165
                        uuid = objCapsule.getString("uuid");
2166
                        capsule = capsuleDao.selectByUuid(uuid);
2167
                        if(capsule == null) {
2168
                            capsule = new Capsule();
2169
                            capsule.setTopicUuid(topic.getUuid());
2170
                            capsule.setUuid(uuid);
2171
                            capsule.setName(objCapsule.getString("name"));
2172
                            capsule.setDescription(objCapsule.getString("description"));
2173
                            capsule.setImage(objCapsule.getString("image"));
2174
                            capsule.setPosition(objCapsule.getInt("position"));
21 gabriel 2175
                            capsule.setAddedOn(objCapsule.getString("added_on"));
2176
                            capsule.setUpdatedOn(objCapsule.getString("updated_on"));
23 gabriel 2177
                           // Log.e("Capsula ","added on"+objCapsule.getString("added_on"));
19 gabriel 2178
                            capsuleDao.insert(capsule);
2179
                        } else {
2180
                            capsule = new Capsule();
2181
                            capsule.setTopicUuid(topic.getUuid());
2182
                            capsule.setName(objCapsule.getString("name"));
2183
                            capsule.setDescription(objCapsule.getString("description"));
2184
                            capsule.setImage(objCapsule.getString("image"));
2185
                            capsule.setPosition(objCapsule.getInt("position"));
21 gabriel 2186
                            capsule.setAddedOn(objCapsule.getString("added_on"));
2187
                            capsule.setUpdatedOn(objCapsule.getString("updated_on"));
23 gabriel 2188
                           // Log.e("Capsula ","added on"+objCapsule.getString("added_on"));
19 gabriel 2189
                            capsuleDao.update(capsule);
2190
                        }
1 gabriel 2191
 
19 gabriel 2192
 
2193
 
2194
 
1 gabriel 2195
                        arraySlides = objCapsule.getJSONArray("slides");
2196
                        for (x = 0; x < arraySlides.length(); x++) {
2197
                            objSlide = arraySlides.getJSONObject(x);
2198
 
19 gabriel 2199
 
2200
                            uuid = objSlide.getString("uuid");
2201
                            slide = slideDao.selectByUuid(uuid);
2202
 
2203
                            if(slide == null) {
2204
 
2205
                                slide = new Slide();
2206
                                slide.setUuid(uuid);
2207
                                slide.setTopicUuid(capsule.getTopicUuid());
2208
                                slide.setCapsuleUuid(capsule.getUuid());
2209
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2210
                                slide.setName(objSlide.getString("name"));
2211
                                slide.setDescription(objSlide.getString("description"));
2212
                                slide.setPosition(objSlide.getInt("position"));
2213
                                slide.setType(objSlide.getString("type"));
2214
                                slide.setFile(objSlide.getString("file"));
2215
                                slide.setBackground(objSlide.getString("background"));
2216
 
2217
                                slideDao.insert(slide);
2218
                            } else {
2219
                                slide.setTopicUuid(capsule.getTopicUuid());
2220
                                slide.setCapsuleUuid(capsule.getUuid());
2221
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2222
                                slide.setName(objSlide.getString("name"));
2223
                                slide.setDescription(objSlide.getString("description"));
2224
                                slide.setPosition(objSlide.getInt("position"));
2225
                                slide.setType(objSlide.getString("type"));
2226
                                slide.setFile(objSlide.getString("file"));
2227
                                slide.setBackground(objSlide.getString("background"));
2228
 
2229
                                slideDao.update(slide);
2230
                            }
1 gabriel 2231
                        }
2232
 
2233
                    }
2234
 
2235
 
2236
                }
2237
            }
2238
 
19 gabriel 2239
            if(data.has( "extended")) {
1 gabriel 2240
 
19 gabriel 2241
                JSONObject objExtended;
2242
                JSONObject objItem;
2243
                JSONArray objItems;
2244
 
2245
 
2246
 
2247
                UserExtended userExtended;
2248
 
2249
                JSONArray extendedCompanies = data.getJSONArray("extended");
2250
                for(i = 0 ; i < extendedCompanies.length(); i++)
2251
                {
2252
                    objExtended = extendedCompanies.getJSONObject(i);
2253
                    if(objExtended.has("details")) {
2254
                        uuid = objExtended.getString("company_uuid");
2255
 
2256
 
2257
                        company = companyDao.selectByUuid(uuid);
2258
                        if (company == null) {
2259
                            company = new Company();
2260
                            company.setUuid(objExtended.getString("company_uuid"));
2261
                            company.setName(objExtended.getString("company_name"));
2262
                            company.setImage(objExtended.getString("company_image"));
2263
 
2264
                            companyDao.insert(company);
2265
                        } else {
2266
                            company.setName(objExtended.getString("company_name"));
2267
                            company.setImage(objExtended.getString("company_image"));
2268
 
2269
                            companyDao.update(company);
2270
                        }
2271
 
2272
                        objItems = objExtended.getJSONArray("details");
2273
                        for(j = 0 ; j < objItems.length(); j++) {
2274
                            objItem = objItems.getJSONObject(j);
2275
 
2276
                            uuid =  objItem.getString("uuid");
2277
 
2278
                            userExtended = userExtendedDao.selectByUuid(uuid);
2279
                            if(userExtended == null) {
2280
                                userExtended = new UserExtended();
2281
                                userExtended.setCompanyUuid(company.getUuid());
2282
                                userExtended.setUuid(uuid);
2283
                                userExtended.setLabel(objItem.getString("label"));
2284
                                userExtended.setValue(objItem.getString("value"));
2285
                                userExtendedDao.insert(userExtended);
2286
                            } else {
2287
                                userExtended.setCompanyUuid(company.getUuid());
2288
                                userExtended.setLabel(objItem.getString("label"));
2289
                                userExtended.setValue(objItem.getString("value"));
2290
                                userExtendedDao.update(userExtended);
2291
                            }
2292
 
2293
 
2294
 
2295
 
2296
                        }
2297
                    }
2298
                }
2299
 
2300
            }
2301
 
2302
 
1 gabriel 2303
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2304
            if(data.has("max_date_changes")) {
2305
                String max_date_changes = data.getString("max_date_changes");
2306
                Log.d("syncFromServer", "max_date_changes : " + max_date_changes);
2307
 
2308
                if(!TextUtils.isEmpty(max_date_changes)) {
2309
                    preference.setMaxDateChanges(max_date_changes);
2310
                }
2311
            } else {
2312
                Log.d("syncFromServer", "No max_date_changes");
2313
            }
2314
 
2315
            Calendar calendar = Calendar.getInstance();
2316
            Date date = calendar.getTime();
2317
 
2318
            String  addedOn = simpleDateFormat.format(date);
2319
 
2320
            List<Company> companies = mAppDatabase.getCompanyDao().selectAll();
2321
            int companySize = companies.size();
2322
 
2323
            if(companySize > 0) {
2324
 
2325
                if(TextUtils.isEmpty(preference.getCompanyUuidActive())) {
2326
 
2327
                    preference.setCompanyUuidActive(companies.get(0).getUuid());
2328
 
2329
                } else {
2330
 
2331
                    boolean companyExist = false;
19 gabriel 2332
                    for(i = 0; i < companies.size(); i++) {
2333
 
2334
                        if (companies.get(i).getUuid().equals(preference.getCompanyUuidActive())) {
1 gabriel 2335
                            companyExist = true;
19 gabriel 2336
                            break;
1 gabriel 2337
                        }
2338
                    }
2339
 
19 gabriel 2340
                    if(!companyExist && companies.size() > 0) {
1 gabriel 2341
                        preference.setCompanyUuidActive(companies.get(0).getUuid());
2342
                    }
2343
                }
2344
 
2345
            } else {
2346
                preference.setCompanyUuidActive("");
2347
            }
2348
 
2349
 
2350
 
2351
            preference.setLastDataRefresh(addedOn);
2352
            preference.setCompanyCount(companySize);
3 gabriel 2353
            preference.save();
1 gabriel 2354
 
2355
        } catch (JSONException e) {
2356
            Log.d(TAG, e.getMessage());
2357
        }
2358
    }
2359
 
2360
    @Override
2361
    public void requestExecuteSyncAdapter() {
2362
            // Pass the settings flags by inserting them in a bundle
2363
            Bundle settingsBundle = new Bundle();
2364
            settingsBundle.putBoolean(
2365
                    ContentResolver.SYNC_EXTRAS_MANUAL, true);
2366
            settingsBundle.putBoolean(
2367
                    ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
2368
 
2369
            ContentResolver.requestSync(mAccount, Constants.AUTHORITY, settingsBundle);
2370
    }
2371
 
2372
 
2373
    private void processResponseServerChanges(String dataString)
2374
    {
2375
 
2376
        Log.d(TAG, "processResponseServerChanges = " + dataString);
2377
 
2378
        try {
2379
            JSONObject objJSON = new JSONObject(dataString);
2380
            boolean success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2381
 
2382
 
2383
            if(success) {
2384
                Calendar calendar = Calendar.getInstance();
2385
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2386
                preference.setLastDataRefresh(simpleDateFormat.format(calendar.getTime()));
3 gabriel 2387
                preference.save();
1 gabriel 2388
 
2389
                String max_date_changes = "";
2390
                boolean processChanges = false;
2391
 
2392
                JSONObject data = objJSON.getJSONObject("data");
11 gabriel 2393
 
2394
 
1 gabriel 2395
                if(data.has("max_date_changes") && data.has("new_capsules")) {
2396
                    int new_capsules = data.getInt("new_capsules");
2397
                    max_date_changes = data.getString("max_date_changes");
2398
 
2399
 
2400
 
2401
 
2402
                    processChanges = new_capsules > 0 && !max_date_changes.equals(preference.getMaxDateChanges());
2403
                } else {
2404
                    processChanges = false;
2405
                }
2406
 
2407
                if(processChanges && !max_date_changes.isEmpty()) {
2408
                    int new_capsules = data.getInt("new_capsules");
2409
                    String message = new_capsules == 1
25 gabriel 2410
                            ? "Hay 1 cápsula disponible"
1 gabriel 2411
                            : "Hay " + new_capsules + " cápsulas disponible";
2412
 
2413
 
25 gabriel 2414
 
2415
 
11 gabriel 2416
                    showMessageSnackBarWithClose(message);
1 gabriel 2417
 
2418
 
2419
                    preference.setMaxDateChanges(max_date_changes);
2420
 
2421
                    if(!isForeground) {
2422
                        String body = new_capsules == 1
25 gabriel 2423
                                ? "Hay 1 cápsula disponible"
1 gabriel 2424
                                : "Hay " + new_capsules + " cápsulas disponible";
44 efrain 2425
                        showFcmNotification("Nuevo contenido", body, new_capsules, "", false);
1 gabriel 2426
                    }
2427
 
2428
                    /*
2429
                    if(!isForeground) {
2430
                        String body = new_capsules == 1
2431
                                ? "Hay 1 cápsula nueva disponible"
2432
                                : "Hay " + new_capsules + " cápsulas disponible";
2433
                        showFcmNotification("Nuevo contenido", body, new_capsules);
2434
 
2435
 
2436
                        AnswerDao answerDao = mAppDatabase.getAnswerDao();
2437
                        answerDao.removeAll();
2438
 
2439
                        QuestionDao questionDao = mAppDatabase.getQuestionDao();
2440
                        questionDao.removeAll();
2441
 
2442
                        QuizDao quizDao = mAppDatabase.getQuizDao();
2443
                        quizDao.removeAll();
2444
 
2445
                        SlideDao slideDao = mAppDatabase.getSlideDao();
2446
                        slideDao.removeAll();
2447
 
2448
                        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
2449
                        capsuleDao.removeAll();
2450
 
2451
                        TopicDao topicDao = mAppDatabase.getTopicDao();
2452
                        topicDao.removeAll();
2453
 
2454
                        CompanyDao companyDao = mAppDatabase.getCompanyDao();
2455
                        companyDao.removeAll();
2456
 
2457
                        UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
2458
                        userExtendedDao.removeAll();
2459
 
2460
 
2461
                        this.syncFromServer(data);
2462
 
2463
 
2464
                        if(!TextUtils.isEmpty(preference.getSlideUuidActive())) {
2465
 
2466
                            Slide slide = mAppDatabase.getSlideDao().selectByUuid(preference.getSlideUuidActive());
2467
                            if(slide == null) {
2468
                                preference.setFragmentIdxActive(Constants.IDX_FRAGMENT_TOPICS);
2469
                                preference.save(this);
2470
                            }
2471
 
2472
                        }
2473
                    }*/
25 gabriel 2474
 
2475
 
1 gabriel 2476
                }
2477
            }
2478
        } catch (JSONException e) {
2479
            Log.d(TAG, e.getMessage());
2480
        }
2481
    }
2482
 
2483
    @Override
2484
    public AppDatabase getDatabase() {
2485
        return mAppDatabase;
2486
    }
2487
 
2488
    @Override
2489
    public void syncToServerOrCheckChanges()
2490
    {
2491
        if(TextUtils.isEmpty(preference.getDeviceUuid())) {
2492
            return;
2493
        }
2494
 
2495
        SyncDao syncDao = mAppDatabase.getSyncDao();
2496
        List<Sync> records = syncDao.selectBatch();
2497
 
2498
        if(records.size() > 0) {
2499
            syncToServer(records);
2500
        } else {
2501
 
2502
                long timeLast = 0;
2503
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2504
                if (!TextUtils.isEmpty(preference.getLastDataRefresh())) {
2505
                    try {
2506
                        timeLast = simpleDateFormat.parse(preference.getLastDataRefresh()).getTime();
2507
                    } catch (Exception e) {
2508
 
2509
                    }
2510
 
2511
                }
2512
 
2513
 
2514
                Calendar calendar = Calendar.getInstance();
2515
                long timeNow = calendar.getTime().getTime();
32 efrain 2516
 
36 gabriel 2517
                if(timeNow > (timeLast + Constants.CHECK_CHANGES_TOKEN_INTERVAL)){
2518
 
2519
                    //Procesamiento en caso que el token no este, check cada 15 minutos.
2520
 
2521
                    if(preference.isRefreshTokenIsRequired()) {
2522
                        FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
32 efrain 2523
                            @Override
2524
                            public void onComplete(@NonNull Task<String> task) {
2525
                                if (!task.isSuccessful()) {
2526
                                    Log.w(TAG, "Fetching FCM registration token failed", task.getException());
2527
                                    return;
2528
                                }
2529
 
2530
                                // Get new FCM registration token
2531
                                String token = task.getResult();
2532
 
2533
                                Log.e("BUG Token", "Token 3 :  " + token);
2534
 
2535
                                createSyncRecordNewToken(token);
2536
 
2537
                                preference.setRefreshTokenIsRequired(false);
2538
                                preference.save();
2539
                            }
2540
                        });
2541
 
2542
 
36 gabriel 2543
                    } else {
32 efrain 2544
 
36 gabriel 2545
                        if (preference.getDeviceToken().isEmpty()) {
2546
                            FirebaseMessaging.getInstance().deleteToken().addOnCompleteListener(new OnCompleteListener<Void>() {
2547
                                @Override
2548
                                public void onComplete(@NonNull Task<Void> task) {
2549
                                    preference.setRefreshTokenIsRequired(true);
2550
                                    preference.save();
32 efrain 2551
 
36 gabriel 2552
                                    Log.e("Esta vacio"," mando delete token");
32 efrain 2553
 
36 gabriel 2554
                                }
2555
                            });
2556
                        }
2557
                    }
2558
                }
32 efrain 2559
 
36 gabriel 2560
                 if (timeNow > (timeLast + Constants.CHECK_CHANGES_INTERVAL)) {
2561
                     //Solicitar revision de cambios cada 4 horas.
1 gabriel 2562
                    requestCheckChanges();
2563
                }
2564
        }
2565
    }
2566
 
2567
 
2568
 
2569
    public void syncToServer(List<Sync> records)
2570
    {
2571
 
2572
 
2573
        int maxRecordsSyncBatch = 0;
2574
        FormBody.Builder formBodyBatchBuilder = new FormBody.Builder();
2575
        formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_DEVICE_UUID, preference.getDeviceUuid());
2576
 
2577
        for(Sync record : records)
2578
        {
2579
 
27 gabriel 2580
           // Log.e("Ingreso a", "syncToServer"+record.getType()+" data"+record.getData());
2581
 
2582
          //  Log.d(TAG, "SyncRecord ID = " + record.getId() + " Data : "  + record.getData() + " Type= " + record.getType());
2583
 
28 gabriel 2584
 
1 gabriel 2585
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {
2586
                Log.d(TAG, "Device");
2587
 
36 gabriel 2588
 
1 gabriel 2589
                try {
2590
                    Http http = new Http(this.getCacheDir());
2591
                    OkHttpClient client = http.getHttpClient(false);
2592
 
2593
                    RequestBody formBody = new FormBody.Builder()
2594
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID,  String.valueOf(Configuration.APPLICATION_ID))
2595
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
2596
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
2597
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
2598
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE  + " " + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName())
2599
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
2600
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
2601
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
2602
                            .build();
2603
 
2604
                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
2605
                    Request request = new Request.Builder()
2606
                            .url(Configuration.URL_DEVICE)
2607
                            .post(formBody)
2608
                            .build();
2609
 
36 gabriel 2610
                    isSyncDevice = true;
2611
 
1 gabriel 2612
                    Call call = client.newCall(request);
2613
                    call.enqueue(new okhttp3.Callback() {
2614
                        public void onResponse(Call call, Response response)
2615
                                throws IOException {
2616
                            Log.d(TAG, "Response Device :  " +  response.body().toString());
36 gabriel 2617
                            isSyncDevice = false;
1 gabriel 2618
 
43 gabriel 2619
                            processResponseSyncToServer(response.body().string(),"device");
1 gabriel 2620
                        }
2621
 
2622
                        public void onFailure(Call call, IOException e) {
2623
                            isSyncDevice = false;
2624
                            Log.d(TAG, "Error :  " +  e.getMessage());
2625
                        }
2626
                    });
2627
                } catch (Exception e) {
2628
                }
2629
            }
2630
 
36 gabriel 2631
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken && !isSyncDevice) {
1 gabriel 2632
                isSyncToken = true;
2633
                Log.d(TAG, "FCM");
27 gabriel 2634
                Log.e("Token a Sync",""+record.getData());
1 gabriel 2635
 
2636
                try {
2637
                    Http http = new Http(this.getCacheDir());
2638
                    OkHttpClient client = http.getHttpClient(false);
2639
 
2640
                    RequestBody formBody = new FormBody.Builder()
2641
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID,preference.getDeviceUuid())
2642
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
2643
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
2644
                            .build();
2645
 
2646
                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
2647
                    Request request = new Request.Builder()
2648
                            .url(Configuration.URL_FCM)
2649
                            .post(formBody)
2650
                            .build();
2651
 
2652
                    Call call = client.newCall(request);
2653
                    call.enqueue(new okhttp3.Callback() {
2654
                        public void onResponse(Call call, Response response)
2655
                                throws IOException {
2656
                            isSyncToken = false;
27 gabriel 2657
                            Log.e("Se envio", "Procesando respuesta");
43 gabriel 2658
                            processResponseSyncToServer(response.body().string(),"");
1 gabriel 2659
                        }
2660
 
2661
                        public void onFailure(Call call, IOException e) {
2662
                            Log.d(TAG, "Error :  " +  e.getMessage());
2663
                            isSyncToken = false;
2664
                        }
2665
                    });
2666
                } catch (Exception e) {
2667
 
2668
 
2669
                }
2670
            }
2671
 
2672
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_SYNC ) {
2673
                Log.d(TAG, "SYNC BATCH");
2674
                maxRecordsSyncBatch++;
2675
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_DATA + maxRecordsSyncBatch, record.getData());
2676
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_SYNC_ID + maxRecordsSyncBatch, String.valueOf(record.getId()));
2677
            }
2678
        }
2679
 
2680
 
2681
        if(maxRecordsSyncBatch > 0 && !isSyncBatch) {
2682
            Log.d(TAG, "Sync Batch");
2683
            isSyncBatch = true;
2684
 
2685
            try {
2686
                Http http = new Http(this.getCacheDir());
2687
                OkHttpClient client = http.getHttpClient(false);
2688
 
2689
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_MAX_RECORDS, String.valueOf(maxRecordsSyncBatch));
2690
                RequestBody formBody = formBodyBatchBuilder.build();
2691
 
2692
                Log.d(TAG, "URL = " + Configuration.URL_SYNC_BATCH);
2693
                Request request = new Request.Builder()
2694
                    .url(Configuration.URL_SYNC_BATCH)
2695
                    .post(formBody)
2696
                    .build();
2697
 
2698
                Call call = client.newCall(request);
2699
                call.enqueue(new okhttp3.Callback() {
2700
                    public void onResponse(Call call, Response response) throws IOException {
2701
                        isSyncBatch = false;
32 efrain 2702
                        processResponseServerBatch(response.body().string());
1 gabriel 2703
                    }
2704
 
2705
                    public void onFailure(Call call, IOException e) {
2706
                        Log.d(TAG, "Error :  " +  e.getMessage());
2707
                        isSyncBatch = false;
2708
                    }
2709
                });
2710
            } catch (Exception e) {
2711
 
2712
 
2713
            }
2714
        }
2715
 
2716
 
2717
    }
2718
 
32 efrain 2719
    private void processResponseServerBatch(String dataString)
1 gabriel 2720
    {
2721
        boolean success = false;
2722
        long sync_id = 0;
2723
 
2724
        Log.d(TAG, "processResponseServer = " + dataString);
2725
        try {
2726
            JSONObject objJSON = new JSONObject(dataString);
2727
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2728
            if(success  && objJSON.has("data")) {
2729
                JSONArray jsonArrayData = objJSON.getJSONArray("data");
2730
 
2731
 
2732
                JSONObject jsonObjectData;
2733
                int max = jsonArrayData.length();
2734
                for(int i = 0; i < max; i++) {
2735
                    jsonObjectData = jsonArrayData.getJSONObject(i);
2736
 
2737
                    if(jsonObjectData.has("success") && jsonObjectData.getBoolean("success")) {
2738
                        sync_id = jsonObjectData.getLong("sync_id");
2739
 
2740
                        mAppDatabase.getSyncDao().remove(sync_id);
2741
 
2742
                    }
2743
 
2744
 
2745
                }
2746
 
2747
                /*
2748
                if(jsonObjectData.has("message")) {
2749
                    message = jsonObjectData.getString("message");
2750
                }
2751
 
2752
                if(jsonObjectData.has("aes")) {
2753
                    preference.setAes(jsonObjectData.getString("aes"));
2754
                    preference.save(this);
2755
                }
2756
 
2757
                if(jsonObjectData.has("password")) {
2758
                    preference.setPassword(jsonObjectData.getString("password"));
2759
                    preference.save(this);
2760
                }
2761
                */
2762
            }
2763
            if(success && sync_id > 0) {
2764
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2765
                mAppDatabase.getSyncDao().remove(sync_id);
28 gabriel 2766
 
1 gabriel 2767
            }
2768
        } catch (JSONException e) {
2769
            e.printStackTrace();
2770
        }
2771
    }
2772
 
43 gabriel 2773
    private void processResponseSyncToServer(String dataString, String origen)
1 gabriel 2774
    {
2775
        boolean success = false;
2776
        long sync_id = 0;
2777
 
2778
        Log.d(TAG, "processResponseServer = " + dataString);
2779
        try {
2780
            JSONObject objJSON = new JSONObject(dataString);
2781
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2782
            if(success  && objJSON.has("data")) {
2783
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
2784
 
32 efrain 2785
 
1 gabriel 2786
                if(jsonObjectData.has("sync_id")) {
2787
                    sync_id = jsonObjectData.getLong("sync_id");
2788
                }
2789
 
2790
                /*
2791
                if(jsonObjectData.has("message")) {
2792
                    message = jsonObjectData.getString("message");
2793
                }
2794
 
2795
                if(jsonObjectData.has("aes")) {
2796
                    preference.setAes(jsonObjectData.getString("aes"));
2797
                    preference.save(this);
2798
                }
2799
 
2800
                if(jsonObjectData.has("password")) {
2801
                    preference.setPassword(jsonObjectData.getString("password"));
2802
                    preference.save(this);
2803
                }
2804
                */
2805
            }
2806
            Log.d(TAG, "SyncID = " + sync_id);
2807
            if(success && sync_id > 0) {
2808
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2809
                mAppDatabase.getSyncDao().remove(sync_id);
43 gabriel 2810
 
2811
                if(origen.equals("device"))
2812
                {
2813
                    syncToServerOrCheckChanges();
2814
 
2815
                }
1 gabriel 2816
            }
2817
        } catch (JSONException e) {
2818
            e.printStackTrace();
2819
        }
2820
    }
2821
 
32 efrain 2822
    /*
27 gabriel 2823
    private void processResponseSyncTokenFCMtoServer(String dataString)
2824
    {
2825
        Log.e("Respuesta",""+dataString);
2826
        boolean success = false;
2827
 
2828
        try {
2829
            JSONObject objJSON = new JSONObject(dataString);
2830
            success = objJSON.has("success") && objJSON.getBoolean("success");
2831
 
2832
            if(success) {
2833
                Log.e("Token almacenado"," en server de manera exitosa");
2834
            }
2835
        } catch (JSONException e) {
2836
            e.printStackTrace();
2837
        }
2838
    }
2839
 
2840
 
32 efrain 2841
     */
27 gabriel 2842
 
32 efrain 2843
 
1 gabriel 2844
    /*
2845
    private void processResponseServerCheckChanges(String dataString) {
2846
 
2847
        Log.d(TAG, "processResponseServerCheckChanges = " + dataString);
2848
 
2849
        runOnUiThread(new Runnable() {
2850
 
2851
            @Override
2852
            public void run() {
2853
 
2854
                try {
2855
                    JSONObject objJSON = new JSONObject(dataString);
2856
                    boolean success = objJSON.has("success") ? objJSON.getBoolean("success") : false;
2857
                    String message = "";
2858
                    if (objJSON.has("data")) {
2859
                        Object item = objJSON.get("data");
2860
                        if (item instanceof String) {
2861
                            message = item.toString();
2862
                        }
2863
                    }
2864
 
2865
                    if (success) {
2866
                        mAppDatabase.getAnswerDao().removeAll();
2867
                        mAppDatabase.getQuestionDao().removeAll();
2868
                        mAppDatabase.getQuizDao().removeAll();
2869
                        mAppDatabase.getSlideDao().removeAll();
2870
                        mAppDatabase.getCapsuleDao().removeAll();
2871
                        mAppDatabase.getTopicDao().removeAll();
2872
 
2873
 
2874
                        JSONObject data = objJSON.getJSONObject("data");
2875
                        syncFromServer(data);
2876
 
2877
 
2878
                    }
2879
 
2880
 
2881
                } catch (JSONException e) {
2882
                    Log.d(TAG, e.getMessage());
2883
                }
2884
 
2885
                reloadNavHeader();
2886
 
2887
 
2888
            }
2889
        });
2890
    }
2891
     */
2892
 
49 gabriel 2893
    private void processResponseServer(String dataString) {
1 gabriel 2894
 
49 gabriel 2895
        Log.d(TAG, "processResponseServer = " + dataString);
1 gabriel 2896
 
49 gabriel 2897
        runOnUiThread(new Runnable() {
2898
 
2899
            @Override
2900
            public void run() {
2901
 
2902
                try {
2903
                    JSONObject objJSON = new JSONObject(dataString);
2904
                    boolean success = objJSON.has("success") ? objJSON.getBoolean("success") : false;
2905
                    String message = "";
2906
                    if (objJSON.has("data")) {
2907
                        Object item = objJSON.get("data");
2908
                        if (item instanceof String) {
2909
                            message = item.toString();
2910
                        }
2911
                    }
2912
 
2913
                    if (success) {
2914
 
2915
                        getDatabase().getAnswerDao().removeAll();
2916
                        getDatabase().getQuestionDao().removeAll();
2917
                        getDatabase().getQuizDao().removeAll();
2918
                        getDatabase().getSlideDao().removeAll();
2919
                        getDatabase().getCapsuleDao().removeAll();
2920
                        getDatabase().getTopicDao().removeAll();
2921
                        getDatabase().getUserExtendedDao().removeAll();
2922
                        getDatabase().getUserLogDao().removeAllUserUuidNotEqual(preference.getUserUuid());
2923
                        getDatabase().getProgressDao().removeAllUserUuidNotEqual(preference.getUserUuid());
2924
 
2925
                        JSONObject data = objJSON.getJSONObject("data");
2926
                        syncFromServer(data);
2927
 
2928
                        preference.setRefreshContentRequired(false);
2929
                        Toast.makeText(getApplicationContext(), "¡Contenido actualizado con exito!", Toast.LENGTH_SHORT).show();
2930
 
2931
                    } else {
2932
                       showMessageSnackBar(message);
2933
                    }
2934
 
2935
 
2936
                } catch (JSONException e) {
2937
                    Log.d(TAG, e.getMessage());
2938
                }
2939
 
2940
 
2941
            }
2942
        });
2943
 
2944
 
2945
    }
2946
 
19 gabriel 2947
}