Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 48 | Rev 50 | 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();
844
                        refreshContent();
43 gabriel 845
                    }
846
                });
847
 
848
 
849
        AlertDialog alertDialog = alertDialogBuilder.create();
850
        alertDialog.show();
851
        alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.teal_700, null));
852
 
853
    }
854
 
1 gabriel 855
    @Override
49 gabriel 856
    protected void onNewIntent(Intent intent) {
857
        super.onNewIntent(intent);
858
 
859
        if(intent.getExtras() != null) {
860
            for (String key : intent.getExtras().keySet()) {
861
                Object value = intent.getExtras().get(key);
862
                if (value.toString().equals("content-refresh")) {
863
                    if (!preference.isRefreshContentRequired()) {
864
                      //  preference.setRefreshContentRequired(true);
865
                        saveNotificationCenterNew("Nuevo contenido para descargar", "", "Tienes nuevas capsulas de aprendizaje para descargar");
866
 
867
                        CartelRefreshContent();
868
                    }
869
                }
870
            }
871
        }
872
    }
873
 
874
    @Override
1 gabriel 875
    public void setConnectedInternet(Boolean isConnected)
876
    {
877
        connected = isConnected;
878
        textViewMessageNotConnection.setVisibility(isConnected ? View.INVISIBLE : View.VISIBLE);
879
    }
880
 
881
    @Override
882
    public boolean isConnectedInternet() {
883
        return connected;
884
    }
885
 
886
    @Override
887
    public void showMessageSnackBar(String message) {
888
        Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_LONG).show();
889
    }
890
 
891
 
892
    @Override
893
    public void showMessageSnackBarWithClose(String message) {
11 gabriel 894
 
1 gabriel 895
        final Snackbar snackBar = Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_INDEFINITE);
896
 
897
        snackBar.setAction(R.string.snackbar_close, new View.OnClickListener() {
898
            @Override
899
            public void onClick(View v) {
900
                // Call your action method here
901
                snackBar.dismiss();
902
            }
903
        });
11 gabriel 904
       snackBar.show();
1 gabriel 905
 
906
 
907
    }
908
 
909
    @Override
910
    public void onErrorFatal() {
911
 
912
 
913
        invokeFragment(Constants.IDX_FRAGMENT_SIGNIN);
914
    }
915
 
916
    @Override
917
    public void invokeFragment(int fragmentIdxActiveNuevo)
918
    {
27 gabriel 919
       // Log.e("Invoco fragmento"," "+fragmentIdxActiveNuevo);
8 gabriel 920
 
1 gabriel 921
        String fragmentKeyActual    = PREFIX_FRAG + preference.getFragmentIdxActive();
922
        String fragmentKeyNuevo 	= PREFIX_FRAG + fragmentIdxActiveNuevo;
923
        preference.setFragmentIdxActive(fragmentIdxActiveNuevo);
3 gabriel 924
        preference.save();
1 gabriel 925
 
926
        Fragment fragment;
927
        if(!fragmentKeyActual.equalsIgnoreCase(fragmentKeyNuevo)) {
928
            if(fragmentHashMap.containsKey(fragmentKeyActual)) {
929
                fragment = fragmentHashMap.get(fragmentKeyActual);
930
                if(fragment != null) {
931
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
932
                    fragmentTransaction.hide(fragment);
3 gabriel 933
                    fragmentTransaction.commitAllowingStateLoss();
1 gabriel 934
                }
935
            }
936
        }
937
 
938
        boolean add = false;
939
        fragment = null;
8 gabriel 940
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
7 gabriel 941
      //  mDrawerToggle.setDrawerIndicatorEnabled(false);
1 gabriel 942
 
943
 
944
        switch(fragmentIdxActiveNuevo) {
945
            case Constants.IDX_FRAGMENT_SIGNIN :
46 gabriel 946
               // badgenotification.setVisibility(View.GONE);
947
 
948
                // getSupportActionBar().hide();
1 gabriel 949
                 if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
950
                     fragment = fragmentHashMap.get(fragmentKeyNuevo);
951
                 } else {
952
                     add = true;
953
                     fragment = new SigninFragment();
954
                 }
955
                break;
956
 
957
            case Constants.IDX_FRAGMENT_TOPICS :
46 gabriel 958
              //  badgenotification.setVisibility(View.GONE);
1 gabriel 959
 
7 gabriel 960
               // getSupportActionBar().show();
961
             //   mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 962
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
963
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
964
                } else {
965
                    add = true;
8 gabriel 966
                    fragment = new TopicFragment();
1 gabriel 967
                }
968
                break;
969
 
9 gabriel 970
            case Constants.IDX_FRAGMENT_NOTIFICATION:
46 gabriel 971
               // badgenotification.setVisibility(View.VISIBLE);
1 gabriel 972
 
9 gabriel 973
                // getSupportActionBar().show();
974
                //   mDrawerToggle.setDrawerIndicatorEnabled(true);
975
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
976
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
977
                } else {
978
                    add = true;
979
                    fragment = new NotificationCenter();
980
                }
981
                break;
982
 
983
 
1 gabriel 984
            case Constants.IDX_FRAGMENT_CAPSULES :
46 gabriel 985
              //  badgenotification.setVisibility(View.GONE);
986
 
987
                //  getSupportActionBar().show();
7 gabriel 988
              //  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1 gabriel 989
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
990
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
991
                } else {
992
                    add = true;
993
                    fragment = new CapsuleFragment();
994
                }
995
                break;
996
 
997
            case Constants.IDX_FRAGMENT_SLIDES :
46 gabriel 998
               // badgenotification.setVisibility(View.GONE);
999
 
1000
                //   getSupportActionBar().show();
7 gabriel 1001
             //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1 gabriel 1002
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1003
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1004
                } else {
1005
                    add = true;
1006
                    fragment = new SlideFragment();
1007
                }
1008
                break;
1009
 
1010
            case Constants.IDX_FRAGMENT_GALLERY :
46 gabriel 1011
               // badgenotification.setVisibility(View.GONE);
1012
 
1013
                //   getSupportActionBar().show();
7 gabriel 1014
             //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1 gabriel 1015
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1016
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1017
                } else {
1018
                    add = true;
1019
                    fragment = new GalleryFragment();
1020
                }
1021
 
1022
                break;
1023
 
1024
            case Constants.IDX_FRAGMENT_FINISH_CAPSULE :
46 gabriel 1025
               // badgenotification.setVisibility(View.GONE);
1026
 
1027
                //  getSupportActionBar().hide();
1 gabriel 1028
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1029
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1030
                } else {
1031
                    add = true;
1032
                    fragment = new FinishCapsuleFragment();
1033
                }
1034
                break;
1035
 
1036
            case Constants.IDX_FRAGMENT_FINISH_TOPIC :
46 gabriel 1037
               // badgenotification.setVisibility(View.GONE);
1038
 
1039
                //  getSupportActionBar().hide();
1 gabriel 1040
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1041
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1042
                } else {
1043
                    add = true;
1044
                    fragment = new FinishTopicFragment();
1045
                }
1046
                break;
1047
 
1048
            case Constants.IDX_FRAGMENT_TIMELINE :
46 gabriel 1049
               // badgenotification.setVisibility(View.GONE);
1050
 
1051
                //  getSupportActionBar().show();
7 gabriel 1052
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1053
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1054
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1055
                } else {
1056
                    add = true;
1057
                    fragment = new TimelineFragment();
1058
                }
1059
                break;
1060
 
1061
            case Constants.IDX_FRAGMENT_COMPANIES:
46 gabriel 1062
               // badgenotification.setVisibility(View.GONE);
1063
 
1064
                //  getSupportActionBar().show();
7 gabriel 1065
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1066
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1067
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1068
                } else {
1069
                    add = true;
1070
                    fragment = new CompanyFragment();
1071
                }
1072
                break;
1073
 
1074
            case Constants.IDX_FRAGMENT_PROGRESS :
46 gabriel 1075
               // badgenotification.setVisibility(View.GONE);
1076
 
1077
                // getSupportActionBar().show();
7 gabriel 1078
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1079
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1080
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1081
                } else {
1082
                    add = true;
1083
                    fragment = new ProgressFragment();
1084
                }
1085
                break;
1086
 
1087
            case Constants.IDX_FRAGMENT_USER_PROFILE:
46 gabriel 1088
               // badgenotification.setVisibility(View.GONE);
1089
 
1090
                // getSupportActionBar().show();
7 gabriel 1091
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1092
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1093
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1094
                } else {
1095
                    add = true;
1096
                    fragment = new UserProfileFragment();
1097
                }
1098
                break;
1099
 
8 gabriel 1100
            case Constants.IDX_FRAGMENT_WELCOME:
46 gabriel 1101
               // badgenotification.setVisibility(View.VISIBLE);
8 gabriel 1102
                // getSupportActionBar().show();
1103
                //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1104
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1105
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1106
                } else {
1107
                    add = true;
1108
                    fragment = new WelcomeFragment();
27 gabriel 1109
                  //  Log.e("Vete"," a welcome");
8 gabriel 1110
                }
1111
                break;
1112
 
1 gabriel 1113
            default :
7 gabriel 1114
               // getSupportActionBar().hide();
46 gabriel 1115
               // badgenotification.setVisibility(View.GONE);
1 gabriel 1116
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1117
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1118
                } else {
1119
                    add = true;
1120
                    fragment = new IntroFragment();
1121
                }
1122
                break;
1123
 
1124
 
1125
        }
1126
 
1127
        if(add) {
1128
            fragmentHashMap.put(fragmentKeyNuevo, fragment);
1129
 
1130
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
1131
            fragmentTransaction.add(R.id.fragment_container, fragment, fragmentKeyNuevo);
3 gabriel 1132
            fragmentTransaction.commitAllowingStateLoss();
1 gabriel 1133
        }
1134
 
1135
 
1136
        if(fragment != null) {
1137
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
1138
            fragmentTransaction.show(fragment);
3 gabriel 1139
            fragmentTransaction.commitAllowingStateLoss();
1 gabriel 1140
        }
1141
 
1142
    }
1143
 
1144
    @Override
1145
    public void changeTopicActive(String topicUuid)
1146
    {
1147
        Log.d(TAG, "changeTopicActive : " + topicUuid);
3 gabriel 1148
       // Log.e("Guardo", "Topico en Main");
1 gabriel 1149
 
1150
        preference.setTopicUuidActive(topicUuid);
1151
        preference.setCapsuleUuidActive("");
1152
        preference.setSlideUuidActive("");
3 gabriel 1153
        preference.save();
1 gabriel 1154
 
1155
        invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
1156
    }
1157
 
1158
    @Override
1159
    public void changeCapsuleActive(String capsuleUuid)
1160
    {
1161
        Log.d(TAG, "changeCapsuleActive : " + capsuleUuid);
1162
 
1163
 
1164
 
1165
        preference.setCapsuleUuidActive(capsuleUuid);
1166
        preference.setSlideUuidActive("");
3 gabriel 1167
        preference.save();
1 gabriel 1168
 
1169
        invokeFragment(Constants.IDX_FRAGMENT_SLIDES);
1170
    }
1171
 
1172
    @Override
1173
    public void changeCompanyActive(String companyUuid)
1174
    {
1175
        Log.d(TAG, "changeCompanyActive : " + companyUuid);
1176
 
1177
        preference.setCompanyUuidActive(companyUuid);
3 gabriel 1178
        preference.save();
1 gabriel 1179
    }
1180
 
1181
    @Override
19 gabriel 1182
    public synchronized void changeSlideActive(String slideUuid, String type, boolean showGallery)
1 gabriel 1183
    {
1184
 
1185
        Log.d(TAG, "changeSlideActive : " + slideUuid);
1186
 
1187
        if(!preference.getSlideUuidActive().equals(slideUuid) && type.equals(Constants.SLIDE_TYPE_IMAGE)) {
1188
            Log.d(TAG, "registerOnPageChangeCallback - createProgressAndSyncRecord");
1189
 
1190
            createProgressAndSyncRecord(slideUuid, true, false, false);
1191
        }
1192
        preference.setSlideUuidActive(slideUuid);
3 gabriel 1193
        preference.save();
1 gabriel 1194
 
1195
 
1196
        if(showGallery) {
1197
            invokeFragment(Constants.IDX_FRAGMENT_GALLERY);
3 gabriel 1198
 
1 gabriel 1199
        }
1200
    }
1201
 
1202
    @Override
1203
    public String getTopicUuidActive()
1204
    {
1205
        return preference.getTopicUuidActive();
1206
    }
1207
 
1208
    @Override
1209
    public String getCapsuleUuidActive()
1210
    {
1211
        return preference.getCapsuleUuidActive();
1212
    }
1213
 
1214
    @Override
1215
    public String getSlideUuidActive()
1216
    {
1217
        return preference.getSlideUuidActive();
1218
    }
1219
 
1220
    @Override
1221
    public String getCompanyUuidActive()
1222
    {
1223
        return preference.getCompanyUuidActive();
1224
    }
1225
 
1226
    @Override
1227
    public void setTitleActionBar(String title)
1228
    {
8 gabriel 1229
 
1 gabriel 1230
        getSupportActionBar().setTitle(title);
1231
    }
1232
 
1233
    @Override
1234
    public synchronized void createProgressAndSyncRecord(String slideUuid, boolean completed, boolean isQuiz, boolean isAudioOrVideo)
1235
    {
1236
        Calendar calendar = Calendar.getInstance();
1237
        Date date = calendar.getTime();
1238
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1239
        String  dateOn = simpleDateFormat.format(date);
1240
 
1241
        SlideDao slideDao = mAppDatabase.getSlideDao();
1242
        Slide slide =  slideDao.selectByUuid(slideUuid);
1243
 
1244
        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1245
        Capsule capsule = capsuleDao.selectByUuid(slide.getCapsuleUuid());
1246
 
1247
        TopicDao topicDao = mAppDatabase.getTopicDao();
1248
        Topic topic = topicDao.selectByUuid(capsule.getTopicUuid());
1249
 
1250
        UserLog userLog;
1251
        UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1252
 
1253
        SyncDao syncDao = mAppDatabase.getSyncDao();
1254
        Sync sync;
1255
 
19 gabriel 1256
        String userUuid = preference.getUserUuid();
1257
 
1 gabriel 1258
        // Progreso y UserLog  del Slide
1259
        ProgressDao progressDao = mAppDatabase.getProgressDao();
19 gabriel 1260
        Progress progressSlide = progressDao.selectBySlideUuidAndUserUuid(slide.getUuid(), userUuid);
1261
        Progress progressCapsule =  progressDao.selectByCapsuleUuidAndUserUuid(slide.getCapsuleUuid(),userUuid);
1262
        Progress progressTopic =  progressDao.selectByTopicUuidAndUserUuid(slide.getTopicUuid(),userUuid);
1 gabriel 1263
 
1264
        int totalSlides = 0;
1265
        int viewSlides = 0;
1266
        double percentaje = 0;
1267
        boolean newRecord = false;
1268
        boolean retakeQuiz = false;
1269
 
1270
        /*** INICIO PROCESO DIAPOSITIVA ***/
1271
        if(progressSlide == null) {
1272
 
1273
            retakeQuiz = false;
1274
 
1275
 
1276
            progressSlide = new Progress();
1277
            progressSlide.setUserUuid(preference.getUserUuid());
1278
            progressSlide.setCompanyUuid(topic.getCompanyUuid());
1279
            progressSlide.setTopicUuid(topic.getUuid());
1280
            progressSlide.setCapsuleUuid(capsule.getUuid());
1281
            progressSlide.setSlideUuid(slide.getUuid());
1282
            progressSlide.setType(Constants.PROGERSS_TYPE_SLIDE);
1283
            progressSlide.setCompleted(completed ? 1 : 0);
1284
            progressSlide.setAddedOn(dateOn);
1285
            progressSlide.setUpdatedOn(dateOn);
1286
            progressDao.insert(progressSlide);
1287
        } else {
1288
            retakeQuiz = true;
1289
 
1290
            if (progressSlide.getCompleted() == 1) {
1291
                progressSlide.setReturningAfterCompleted(progressSlide.getReturningAfterCompleted() + 1);
1292
            } else {
1293
                if (completed) {
1294
                    //0 y 1 para Boolean
1295
                    progressSlide.setCompleted(completed  ? 1 : 0);
1296
                } else {
1297
                    progressSlide.setReturning(progressSlide.getReturning() + 1);
1298
                }
1299
            }
1300
 
1301
            progressSlide.setUpdatedOn(dateOn);
1302
            progressDao.update(progressSlide);
1303
        }
1304
 
1305
 
3 gabriel 1306
 
1 gabriel 1307
        /*** FIN PROCESO DIAPOSITIVA ***/
1308
 
1309
 
1310
 
1311
        /*** INICIO PROCESO TOPICO ***/
1312
        ResultCount resultCount;
1313
 
1314
 
1315
        resultCount = slideDao.getCountByTopicUuid(slide.getTopicUuid());
1316
        totalSlides = resultCount.getCount();
1317
 
19 gabriel 1318
        resultCount = progressDao.getCountSlidesCompletedByTopicUuidAndUserUuid(slide.getTopicUuid(), userUuid);
1 gabriel 1319
        viewSlides =  resultCount.getCount();
1320
        if(totalSlides == 0) {
1321
            percentaje = 0;
1322
        } else {
1323
            percentaje = (viewSlides * 100) / totalSlides;
1324
        }
1325
 
1326
        if(progressTopic == null) {
1327
            newRecord = true;
1328
            progressTopic = new Progress();
1329
            progressTopic.setUserUuid(preference.getUserUuid());
1330
            progressTopic.setCompanyUuid( topic.getCompanyUuid());
1331
            progressTopic.setTopicUuid (topic.getUuid());
1332
 
1333
            progressTopic.setViewSlides(viewSlides);
1334
            progressTopic.setTotalSlides(totalSlides);
1335
            progressTopic.setProgress (percentaje);
1336
            progressTopic.setType(Constants.PROGERSS_TYPE_TOPIC);
1337
 
1338
            progressTopic.setAddedOn(dateOn);
1339
            progressTopic.setUpdatedOn(dateOn);
1340
             progressDao.insert(progressTopic);
1341
        } else {
1342
            newRecord = false;
1343
            progressTopic.setViewSlides(viewSlides);
1344
            progressTopic.setTotalSlides(totalSlides);
1345
            progressTopic.setProgress (percentaje);
1346
            progressDao.update(progressTopic);
1347
        }
1348
 
1349
        try {
1350
            JSONObject json = progressTopic.toJson();
1351
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1352
 
1353
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1354
            syncDao.insert(sync);
1355
        } catch (JSONException e) {
1356
        }
1357
 
1358
        if(newRecord) {
1359
            userLog = new UserLog();
1360
            userLog.setUserUuid(preference.getUserUuid());
1361
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_TOPIC);
1362
            userLog.setCompanyUuid (topic.getCompanyUuid());
1363
            userLog.setTopicUuid (topic.getUuid());
1364
            userLog.setAddedOn(dateOn);
1365
 
1366
 
1367
            userLogDao.insert(userLog);
1368
            try {
1369
                JSONObject json = userLog.toJson();
1370
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1371
 
1372
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1373
                syncDao.insert(sync);
1374
            } catch (JSONException e) {
1375
            }
1376
        }
1377
        /*** FIN PROCESO TOPICO ***/
1378
 
1379
 
1380
 
1381
        /*** INICIO PROCESO CAPSULA ***/
1382
        resultCount = slideDao.getCountByCapsuleUuid(slide.getCapsuleUuid());
1383
        totalSlides = resultCount.getCount();
19 gabriel 1384
        resultCount = progressDao.getCountSlidesCompletedByCapsuleUuidAndUserUuid(slide.getCapsuleUuid(), userUuid);
1 gabriel 1385
        viewSlides =  resultCount.getCount();
1386
        if(totalSlides == 0) {
1387
            percentaje = 0;
1388
        } else {
1389
            percentaje = (viewSlides * 100) / totalSlides;
1390
        }
1391
 
1392
        if(progressCapsule == null) {
1393
            newRecord = true;
1394
            progressCapsule = new Progress();
1395
            progressCapsule.setUserUuid(preference.getUserUuid());
1396
            progressCapsule.setCompanyUuid(topic.getCompanyUuid());
1397
            progressCapsule.setTopicUuid(topic.getUuid());
1398
            progressCapsule.setCapsuleUuid (capsule.getUuid());
1399
            progressCapsule.setViewSlides(viewSlides);
1400
            progressCapsule.setTotalSlides(totalSlides);
1401
            progressCapsule.setProgress(percentaje);
1402
            progressCapsule.setType(Constants.PROGERSS_TYPE_CAPSULE);
1403
            progressCapsule.setAddedOn(dateOn);
1404
            progressCapsule.setUpdatedOn(dateOn);
1405
            progressDao.insert(progressCapsule);
1406
 
1407
            Log.d(TAG, "Progress Capsule Nueva : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1408
            preference.setLastCapsuleUuidActive(capsule.getUuid());
1409
        } else {
1410
            newRecord = false;
1411
            progressCapsule.setViewSlides(viewSlides);
1412
            progressCapsule.setTotalSlides(totalSlides);
1413
            progressCapsule.setProgress(percentaje);
1414
 
1415
            Log.d(TAG, "Progress Capsule : getLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1416
            Log.d(TAG, "Progress Capsule : CapsuleActive : " + preference.getCapsuleUuidActive());
1417
 
1418
            if (!preference.getLastCapsuleUuidActive().equals(preference.getCapsuleUuidActive())) {
1419
 
1420
                Log.d(TAG, "Capsule Progress : " + progressCapsule.getProgress());
1421
                Log.d(TAG, "Capsule Completed : " + progressCapsule.getCompleted());
1422
                Log.d(TAG, "Capsule Total slides : " + progressCapsule.getTotalSlides());
1423
                Log.d(TAG, "Capsule View slides : " + progressCapsule.getViewSlides());
1424
 
1425
                if(progressCapsule.getCompleted() == 1) {
1426
                    Log.d(TAG, "Capsule OLD returningAfterCompleted = " + progressCapsule.getReturningAfterCompleted());
1427
 
1428
                    int returningAfterCompleted = progressCapsule.getReturningAfterCompleted() + 1;
1429
 
1430
                    Log.d(TAG, "Capsule NEW returningAfterCompleted = " + returningAfterCompleted);
1431
                    progressCapsule.setReturningAfterCompleted(returningAfterCompleted);
1432
                }
1433
 
1434
                preference.setLastCapsuleUuidActive(capsule.getUuid());
3 gabriel 1435
                preference.save();
1 gabriel 1436
 
1437
                Log.d(TAG, "Progress Capsule : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1438
            }
1439
 
1440
            progressDao.update(progressCapsule);
1441
        }
1442
        try {
1443
            JSONObject json = progressCapsule.toJson();
1444
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1445
 
1446
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1447
            syncDao.insert(sync);
1448
        } catch (JSONException e) {
1449
 
1450
        }
1451
 
1452
        if(newRecord) {
1453
            userLog = new UserLog();
1454
            userLog.setUserUuid(preference.getUserUuid());
1455
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_CAPSULE);
1456
            userLog.setCompanyUuid(topic.getCompanyUuid());
1457
            userLog.setTopicUuid(topic.getUuid());
1458
            userLog.setCapsuleUuid(capsule.getUuid());
1459
            userLog.setAddedOn(dateOn);
1460
 
1461
 
1462
            userLogDao.insert(userLog);
1463
            try {
1464
                JSONObject json = userLog.toJson();
1465
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1466
 
1467
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1468
                syncDao.insert(sync);
1469
            } catch (JSONException e) {
1470
            }
1471
        }
1472
 
1473
 
1474
        /*** FIN PROCESO CAPSULA ***/
1475
 
1476
        /*** INICIO USERLOG SLIDE ***/
1477
        userLog = new UserLog();
1478
        userLog.setUserUuid(preference.getUserUuid());
1479
        userLog.setActivity(Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1480
        userLog.setCompanyUuid(topic.getCompanyUuid());
1481
        userLog.setTopicUuid(topic.getUuid());
1482
        userLog.setCapsuleUuid(capsule.getUuid());
1483
        userLog.setSlideUuid(slide.getUuid());
1484
        userLog.setAddedOn(dateOn);
1485
 
1486
 
1487
        userLogDao.insert(userLog);
1488
        try {
1489
            JSONObject json = userLog.toJson();
1490
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1491
 
1492
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1493
            syncDao.insert(sync);
1494
        } catch (JSONException e) {
1495
        }
1496
 
1497
        /*** FIN ***/
1498
 
1499
 
1500
        /*** PROGRESS SLIDE***/
1501
        try {
1502
            JSONObject json = progressSlide.toJson();
1503
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1504
 
1505
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1506
            syncDao.insert(sync);
1507
        } catch (JSONException e) {
1508
        }
1509
 
1510
        /** IS SLIDE = QUIZ **/
1511
        if (isQuiz) {
1512
            userLog = new UserLog();
1513
            userLog.setUserUuid(preference.getUserUuid());
1514
            userLog.setActivity(retakeQuiz ? Constants.USER_LOG_ACTIVITY_RETAKE_A_TEST : Constants.USER_LOG_ACTIVITY_TAKE_A_TEST);
1515
            userLog.setCompanyUuid (topic.getCompanyUuid());
1516
            userLog.setTopicUuid(slide.getTopicUuid());
1517
            userLog.setCapsuleUuid(slide.getCapsuleUuid());
1518
            userLog.setSlideUuid(slide.getUuid());
1519
            userLog.setAddedOn(dateOn);
1520
 
1521
            userLogDao.insert(userLog);
1522
            try {
1523
                JSONObject json = userLog.toJson();
1524
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1525
 
1526
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1527
                syncDao.insert(sync);
1528
            } catch (JSONException e) {
1529
            }
1530
 
1531
 
1532
            if(progressSlide.getCompleted() == 1) {
1533
                userLog = new UserLog();
1534
                userLog.setUserUuid(preference.getUserUuid());
1535
                userLog.setActivity(Constants.USER_LOG_ACTIVITY_APPROVED_TEST);
1536
                userLog.setCompanyUuid(topic.getCompanyUuid());
1537
                userLog.setTopicUuid(slide.getTopicUuid());
1538
                userLog.setCapsuleUuid(slide.getCapsuleUuid());
1539
                userLog.setSlideUuid(slide.getUuid());
1540
                userLog.setAddedOn(dateOn);
1541
 
1542
                userLogDao.insert(userLog);
1543
                try {
1544
                    JSONObject json = userLog.toJson();
1545
                    json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1546
 
1547
                    sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1548
                    syncDao.insert(sync);
1549
                } catch (JSONException e) {
1550
                }
1551
 
1552
            } else {
1553
                if(progressSlide.getCompleted() == 1) {
1554
                    userLog = new UserLog();
1555
                    userLog.setUserUuid(preference.getUserUuid());
1556
                    userLog.setActivity( Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1557
                    userLog.setCompanyUuid(topic.getCompanyUuid());
1558
                    userLog.setTopicUuid(slide.getTopicUuid());
1559
                    userLog.setCapsuleUuid(slide.getCapsuleUuid());
1560
                    userLog.setSlideUuid(slide.getUuid());
1561
                    userLog.setAddedOn(dateOn);
1562
 
1563
                    userLogDao.insert(userLog);
1564
                    try {
1565
                        JSONObject json = userLog.toJson();
1566
                        json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1567
 
1568
                        sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1569
                        syncDao.insert(sync);
1570
                    } catch (JSONException e) {
1571
                    }
1572
                }
1573
            }
1574
        }
1575
 
1576
        requestExecuteSyncAdapter();
1577
    }
1578
 
1579
    @Override
1580
    public void launchVideoViewer(String videoAudioUrl)
1581
    {
1582
 
3 gabriel 1583
        Intent intent = new Intent(getApplicationContext(), VideoAudioActivity.class);
1 gabriel 1584
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1585
        intent.putExtra("deviceId", preference.getDeviceUuid());
1586
        intent.putExtra("password", preference.getPassword());
1587
        //startActivityForResult(intent, Constants.REQUEST_CODE_VIDEO);
1588
 
1589
        mLauncher.launch(intent);
1590
 
1591
    }
1592
 
1593
    @Override
1594
    public void launchAudioViewer(String videoAudioUrl)
1595
    {
1596
 
3 gabriel 1597
        Intent intent = new Intent(getApplicationContext(), VideoAudioActivity.class);
1 gabriel 1598
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1599
        intent.putExtra("deviceId", preference.getDeviceUuid());
1600
        intent.putExtra("password", preference.getPassword());
1601
        //startActivityForResult(intent, Constants.REQUEST_CODE_AUDIO);
1602
 
1603
 
1604
        mLauncher.launch(intent);
1605
    }
1606
 
1607
    @Override
1608
    public void launchTextViewer(String description)
1609
    {
3 gabriel 1610
        Intent intent = new Intent(getApplicationContext(),TextActivity.class);
1 gabriel 1611
        intent.putExtra("description",description);
1612
 
1613
        //startActivityForResult(intent, Constants.REQUEST_CODE_TEXT);
1614
 
1615
        mLauncher.launch(intent);
1616
    }
1617
 
1618
 
1619
    @Override
1620
    public void launchDocumentViewer(String file)
1621
    {
1622
 
3 gabriel 1623
        Intent intent = new Intent(getApplicationContext(),PdfActivity.class);
1 gabriel 1624
        intent.putExtra("documentUrl",file);
1625
        intent.putExtra("deviceId", preference.getDeviceUuid());
1626
        intent.putExtra("password", preference.getPassword());
1627
 
1628
        //startActivityForResult(intent, Constants.REQUEST_CODE_PDF);
1629
 
1630
        mLauncher.launch(intent);
1631
    }
1632
 
1633
    @Override
1634
    public void launchQuizViewer(String quizUuid)
1635
    {
1636
        ProgressDao progressDao = mAppDatabase.getProgressDao();
19 gabriel 1637
        Progress progress = progressDao.selectBySlideUuidAndUserUuid(preference.getSlideUuidActive(), preference.getUserUuid());
1 gabriel 1638
 
1639
        boolean launch = false;
1640
        if(progress != null && progress.getCompleted() == 0) {
1641
 
1642
            Calendar calendar = Calendar.getInstance();
1643
            Date date = calendar.getTime();
1644
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1645
            try {
1646
                Long updateOn = simpleDateFormat.parse(progress.getUpdatedOn()).getTime();
1647
 
1648
                //30 minutes
1649
                long mintime = 30 * 60 * 1000;
1650
                if(date.getTime() - updateOn >  mintime ) {
1651
                    launch = true;
1652
                }
1653
 
1654
                launch = true;
1655
 
1656
            } catch(Exception e) {
1657
 
1658
            }
1659
 
1660
 
1661
        } else {
1662
            launch = true;
1663
        }
1664
 
1665
        if(launch) {
1666
 
1667
            QuizDao quizDao = mAppDatabase.getQuizDao();
1668
            Quiz quiz = quizDao.selectByUuid(quizUuid);
1669
 
1670
            TopicDao topicDao = mAppDatabase.getTopicDao();
1671
            Topic topic = topicDao.selectByUuid(preference.getTopicUuidActive());
1672
 
1673
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1674
            Capsule capsule = capsuleDao.selectByUuid(preference.getCapsuleUuidActive());
1675
 
1676
            SlideDao slideDao = mAppDatabase.getSlideDao();
1677
            Slide slide = slideDao.selectByUuid(preference.getSlideUuidActive());
1678
 
1679
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1680
            List<Question> questions = questionDao.selectAllByQuizUuid(quiz.getUuid());
1681
 
1682
 
1683
            List<Answer> answers;
1684
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1685
 
3 gabriel 1686
            Intent intent = new Intent(getApplicationContext(), QuizActivity.class);
1 gabriel 1687
           // intent.putExtra("companyUuid", topic.getCompanyUuid());
1688
           // intent.putExtra("topicUuid", topic.getUuid());
1689
            //intent.putExtra("capsuleUuid", capsule.getUuid());
1690
            //intent.putExtra("slideUuid", slide.getUuid());
1691
            //intent.putExtra("userUuid", preference.getUserUuid());
1692
            //intent.putExtra("quizUuid", quizUuid);
1693
 
1694
 
1695
            intent.putExtra("quiz_uuid", quiz.getUuid());
1696
            intent.putExtra("quiz_company_uuid", quiz.getCompanyUuid());
1697
            intent.putExtra("quiz_name", quiz.getName());
1698
            intent.putExtra("quiz_points", quiz.getPoints());
1699
            intent.putExtra("quiz_max_time", quiz.getMaxTime());
1700
            intent.putExtra("quiz_minimum_points_required", quiz.getMinimumPointsRequired());
1701
            intent.putExtra("quiz_failed", quiz.getFailed());
1702
            intent.putExtra("quiz_text", quiz.getText());
1703
 
1704
            intent.putExtra("questions", questions.size());
1705
            int i = 1;
1706
            int j = 1;
1707
            for(Question question : questions) {
1708
                intent.putExtra("question" + i + "_uuid", question.getUuid());
1709
                intent.putExtra("question" + i + "_text", question.getText());
1710
                intent.putExtra("question" + i + "_max_length", question.getMaxlength());
1711
                intent.putExtra("question" + i + "_position", question.getPosition());
1712
                intent.putExtra("question" + i + "_points", question.getPoints());
1713
                intent.putExtra("question" + i + "_type", question.getType());
1714
 
1715
                answers = answerDao.selectAllByQuestionUuid(question.getUuid());
1716
                intent.putExtra("question" + i + "_answers", answers.size());
1717
 
1718
                j = 1;
1719
                for(Answer answer : answers) {
1720
                    intent.putExtra("question" + i + "_answer_uuid" + j, answer.getUuid());
1721
                    intent.putExtra("question" + i + "_answer_text" + j, answer.getText());
1722
                    intent.putExtra("question" + i + "_answer_points" + j, answer.getPoints());
1723
                    intent.putExtra("question" + i + "_answer_correct" + j, answer.getCorrect());
1724
                    j++;
1725
                }
1726
 
1727
                i++;
1728
            }
1729
 
1730
 
1731
 
1732
            //startActivityForResult(intent, Constants.REQUEST_CODE_QUIZ);
1733
 
1734
            mLauncher.launch(intent);
1735
        } else {
1736
            showMessageSnackBar(getString(R.string.error_retry_quiz_min_time));
1737
        }
1738
    }
1739
 
1740
 
1741
    @Override
1742
    public Preference getPreference() {
1743
        return preference;
1744
    }
1745
 
49 gabriel 1746
    public void refreshContent(){
1 gabriel 1747
 
49 gabriel 1748
        try {
1749
            TimeZone timeZone = TimeZone.getTimeZone("UTC");
1750
            Calendar calendar = Calendar.getInstance(timeZone);
1751
            TimeZone tz = calendar.getTimeZone();
1752
            int created = (int) (calendar.getTimeInMillis() / 1000);
1753
 
1754
            Random random = new Random(created);
1755
            int rand = 1000 + random.nextInt(8999);
1756
 
1757
 
1758
            Log.d(TAG, "token = " + preference.getDeviceUuid());
1759
            Log.d(TAG, "created = " + created);
1760
            Log.d(TAG, "rand = " + rand);
1761
            Log.d(TAG, "calc = " + preference.getPassword() + ':' + created + ':' + rand);
1762
 
1763
            String secret = MD5.generar(preference.getPassword() + ':' + created + ':' + rand);
1764
 
1765
            Log.d(TAG, "secret = " + secret);
1766
 
1767
            Log.d(TAG, "URL = " + Configuration.URL_REFRESH);
1768
            Request request = new Request.Builder()
1769
                    .url(Configuration.URL_REFRESH)
1770
                    .build();
1771
 
1772
            Http http = new Http(getCacheDir(), preference.getDeviceUuid(), secret, created, rand);
1773
            OkHttpClient client = http.getHttpClient(false);
1774
 
1775
            Call call = client.newCall(request);
1776
            call.enqueue(new Callback() {
1777
                public void onResponse(Call call, Response response)
1778
                        throws IOException {
1779
                    processResponseServer(response.body().string());
1780
 
1781
                }
1782
 
1783
                public void onFailure(Call call, IOException e) {
1784
                    Log.d(TAG, "Error :  " + e.getMessage());
1785
                }
1786
            });
1787
 
1788
        } catch (Exception e) {
1789
           showMessageSnackBar(e.getMessage());
1790
        }
1791
    }
1792
 
1 gabriel 1793
    public void requestCheckChanges()
1794
    {
1795
        Log.d(TAG, "requestCheckChanges");
1796
        try {
1797
 
1798
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1799
            List<Capsule> capsules = capsuleDao.selectAll();
1800
 
1801
            if(capsules.size() > 0) {
1802
                //ArrayList<String> ids = new ArrayList<>();
1803
 
1804
                TimeZone timeZone = TimeZone.getTimeZone("UTC");
1805
                Calendar calendar = Calendar.getInstance(timeZone);
1806
                TimeZone tz = calendar.getTimeZone();
1807
                int created =  (int) (calendar.getTimeInMillis() / 1000);
1808
 
1809
                Random random = new Random(created);
1810
                int rand = 1000 + random.nextInt(8999);
1811
 
1812
 
1813
                //Log.d("requestCheckChanges", "token = " + preference.getDeviceUuid());
1814
                //Log.d("requestCheckChanges", "created = " + created);
1815
               // Log.d("requestCheckChanges", "rand = " + rand);
1816
                //Log.d("requestCheckChanges", "calc = " + preference.password + ':' +  created + ':' + rand);
1817
 
1818
                String secret = MD5.generar(preference.getPassword() + ':' +  created + ':' + rand);
1819
 
1820
                //Log.d("requestCheckChanges", "secret = " + secret);
1821
 
1822
 
1823
                FormBody.Builder formBodyCheckChangeBuilder = new FormBody.Builder();
1824
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_DEVICE_UUID, preference.getDeviceUuid());
1825
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_DATE_CHANGES, preference.getMaxDateChanges());
1826
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_IS_FOREGROUND, String.valueOf(isForeground ? 1 : 0));
1827
                Http http = new Http(this.getCacheDir(), preference.getDeviceUuid(), secret, created, rand);
1828
                OkHttpClient client = http.getHttpClient(false);
1829
 
1830
 
1831
 
1832
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(capsules.size()));
1833
                //formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(0));
1834
 
1835
              int i = 1;
1836
                for(Capsule capsule : capsules)
1837
                {
1838
                    Log.d("requestCheckChanges", "id" + i + " = " + capsule.getTopicUuid() + "|" + capsule.getUuid());
1839
 
1840
 
1841
                    formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_ID + i, capsule.getTopicUuid() + "|" + capsule.getUuid());
1842
                    i++;
1843
                }
1844
 
1845
 
1846
 
1847
                RequestBody formBody = formBodyCheckChangeBuilder.build();
1848
 
1849
                Log.d(TAG, "URL = " + Configuration.URL_CHECK_CHANGES);
1850
                Request request = new Request.Builder()
1851
                        .url(Configuration.URL_CHECK_CHANGES)
1852
                        .post(formBody)
1853
                        .build();
1854
 
1855
                Call call = client.newCall(request);
1856
                call.enqueue(new okhttp3.Callback() {
1857
                    public void onResponse(Call call, Response response)
1858
                            throws IOException {
1859
 
1860
 
1861
 
1862
                        processResponseServerChanges(response.body().string());
1863
                    }
1864
 
1865
                    public void onFailure(Call call, IOException e) {
1866
                        Log.d(TAG, "Error :  " +  e.getMessage());
1867
                    }
1868
                });
1869
            }
1870
 
1871
 
1872
 
1873
        } catch(Exception e) {
1874
 
1875
        }
1876
    }
1877
 
1878
 
1879
    public void syncFromServer(JSONObject data)
1880
    {
1881
        try {
1882
            JSONObject objUser = data.getJSONObject("user");
1883
            String userUuid = objUser.getString("uuid");
1884
 
1885
 
1886
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1887
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1888
            QuizDao quizDao = mAppDatabase.getQuizDao();
1889
            SlideDao slideDao = mAppDatabase.getSlideDao();
1890
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1891
            TopicDao topicDao = mAppDatabase.getTopicDao();
1892
            CompanyDao companyDao = mAppDatabase.getCompanyDao();
1893
            UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
1894
 
1895
 
1896
 
1897
            ProgressDao progressDao = mAppDatabase.getProgressDao();
1898
            progressDao.removeAllUserUuidNotEqual(userUuid);
1899
 
1900
 
1901
            UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1902
            userLogDao.removeAllUserUuidNotEqual(userUuid);
1903
 
1904
            JSONArray arrayCapsules;
1905
            JSONArray arraySlides;
1906
            JSONArray arrayAnswers;
1907
            JSONArray arrayQuestions;
1908
            JSONArray arrayProgress;
1909
            JSONArray arrayQuizzes;
1910
            JSONArray arrayUserLog;
1911
 
1912
            JSONObject objTopic;
1913
            JSONObject objCapsule;
1914
            JSONObject objSlide;
1915
            JSONObject objAnswer;
1916
            JSONObject objQuestion;
1917
            JSONObject objQuiz;
1918
            JSONObject objProgress;
1919
            JSONObject objUserLog;
1920
            int i,j,x;
1921
 
1922
            if(data.has("progress")) {
1923
 
1924
                arrayProgress = data.getJSONArray("progress");
1925
                for (i = 0; i < arrayProgress.length(); i++) {
1926
                    objProgress = arrayProgress.getJSONObject(i);
1927
 
1928
 
1929
                    Progress progress = null;
1930
 
1931
 
1932
                    userUuid = objProgress.getString("user_uuid");
1933
                    String type = objProgress.getString("type");
1934
                    String topicUuid = objProgress.getString("topic_uuid");
1935
                    String capsuleUuid = objProgress.getString("capsule_uuid");
1936
                    String slideUuid = objProgress.getString("slide_uuid");
1937
 
1938
                    if(type == Constants.PROGERSS_TYPE_SLIDE) {
1939
                        progress = progressDao.selectBySlideUuidAndUserUuid(slideUuid, userUuid);
1940
                    } else if(type == Constants.PROGERSS_TYPE_CAPSULE) {
1941
                        progress = progressDao.selectByCapsuleUuidAndUserUuid(capsuleUuid, userUuid);
1942
                    } else if(type == Constants.PROGERSS_TYPE_TOPIC) {
1943
                        progress = progressDao.selectByTopicUuidAndUserUuid(topicUuid, userUuid);
1944
                    }
1945
 
1946
 
1947
                    if(progress == null) {
1948
                        progress = new Progress();
1949
                        progress.setUserUuid(userUuid);
1950
                        progress.setCompanyUuid(objProgress.getString("company_uuid"));
1951
                        progress.setTopicUuid(topicUuid);
1952
                        progress.setCapsuleUuid(capsuleUuid);
1953
                        progress.setSlideUuid(slideUuid);
1954
                        progress.setProgress(objProgress.getDouble("progress"));
1955
                        progress.setTotalSlides(objProgress.getInt("total_slides"));
1956
                        progress.setViewSlides(objProgress.getInt("view_slides"));
1957
                        progress.setType(type);
1958
                        progress.setReturning(objProgress.getInt("returning"));
1959
                        progress.setReturningAfterCompleted(objProgress.getInt("returning_after_completed"));
1960
                        progress.setCompleted(objProgress.getInt("completed"));
1961
                        progress.setAddedOn(objProgress.getString("added_on"));
1962
                        progress.setUpdatedOn(objProgress.getString("updated_on"));
1963
 
1964
                        progressDao.insert(progress);
1965
                    }
1966
 
1967
 
1968
                }
1969
            }
1970
 
1971
            if(data.has("userlog")) {
1972
                arrayUserLog = data.getJSONArray("userlog");
1973
                for (i = 0; i < arrayUserLog.length(); i++) {
1974
                    objUserLog = arrayUserLog.getJSONObject(i);
1975
 
1976
                    userUuid = objUserLog.getString("user_uuid");
1977
                    String activity = objUserLog.getString("activity");
1978
                    String added_on = objUserLog.getString("added_on");
1979
 
1980
                    UserLog userLog = userLogDao.selectOneByUserUuidAndActivityAndAddedOn(userUuid, activity, added_on);
1981
                    if(userLog == null) {
1982
                        userLog = new UserLog();
1983
                        userLog.setUserUuid(objUserLog.getString("user_uuid"));
1984
                        userLog.setCompanyUuid(objUserLog.getString("company_uuid"));
1985
                        userLog.setTopicUuid(objUserLog.getString("topic_uuid"));
1986
                        userLog.setCapsuleUuid(objUserLog.getString("capsule_uuid"));
1987
                        userLog.setSlideUuid(objUserLog.getString("slide_uuid"));
1988
                        userLog.setActivity(objUserLog.getString("activity"));
1989
                        userLog.setAddedOn(objUserLog.getString("added_on"));
1990
                        userLogDao.insert(userLog);
1991
                    }
1992
                }
1993
            }
1994
 
19 gabriel 1995
            String uuid;
1996
            Company company;
1 gabriel 1997
            if(data.has("quizzes")) {
19 gabriel 1998
                Quiz quiz;
1999
                Question question;
2000
                Answer answer;
2001
 
1 gabriel 2002
                arrayQuizzes = data.getJSONArray("quizzes");
2003
                for (i = 0; i < arrayQuizzes.length(); i++) {
2004
                    objQuiz = arrayQuizzes.getJSONObject(i);
19 gabriel 2005
                    uuid = objQuiz.getString("company_uuid");
2006
                    company = companyDao.selectByUuid(uuid);
1 gabriel 2007
                    if (company == null) {
2008
                        company = new Company();
2009
                        company.setUuid(objQuiz.getString("company_uuid"));
2010
                        company.setName(objQuiz.getString("company_name"));
2011
                        company.setImage(objQuiz.getString("company_image"));
2012
 
2013
                        companyDao.insert(company);
19 gabriel 2014
                    } else {
2015
                        company.setName(objQuiz.getString("company_name"));
2016
                        company.setImage(objQuiz.getString("company_image"));
2017
 
2018
                        companyDao.update(company);
1 gabriel 2019
                    }
2020
 
19 gabriel 2021
                    uuid =  objQuiz.getString("uuid");
2022
                    quiz = quizDao.selectByUuid(uuid);
1 gabriel 2023
 
19 gabriel 2024
                    if(quiz == null) {
2025
                        quiz = new Quiz();
2026
                        quiz.setUuid(  objQuiz.getString("uuid"));
2027
                        quiz.setCompanyUuid(  company.getUuid() );
2028
                        quiz.setFailed(  objQuiz.getString("failed"));
2029
                        quiz.setName(  objQuiz.getString("name"));
2030
                        quiz.setText(  objQuiz.getString("text"));
2031
                        quiz.setPoints(  objQuiz.getInt("points"));
2032
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2033
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2034
                        quizDao.insert(quiz);
2035
 
2036
                    } else {
2037
                        quiz.setCompanyUuid(  company.getUuid() );
2038
                        quiz.setFailed(  objQuiz.getString("failed"));
2039
                        quiz.setName(  objQuiz.getString("name"));
2040
                        quiz.setText(  objQuiz.getString("text"));
2041
                        quiz.setPoints(  objQuiz.getInt("points"));
2042
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2043
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2044
                        quizDao.update(quiz);
2045
                    }
2046
 
1 gabriel 2047
                    arrayQuestions = objQuiz.getJSONArray("questions");
2048
                    for (j = 0; j < arrayQuestions.length(); j++) {
2049
                        objQuestion = arrayQuestions.getJSONObject(j);
2050
 
19 gabriel 2051
                        uuid = objQuestion.getString("uuid");
2052
                        question = questionDao.selectByUuid(uuid);
2053
                        if(question == null) {
2054
                            question = new Question();
2055
                            question.setQuizUuid( quiz.getUuid());
2056
                            question.setUuid(uuid) ;
2057
                            question.setText( objQuestion.getString("text"));
2058
                            question.setType( objQuestion.getString("type"));
2059
                            question.setPoints( objQuestion.getInt("points"));
2060
                            question.setMaxlength( objQuestion.getInt("maxlength"));
1 gabriel 2061
 
19 gabriel 2062
                            questionDao.insert(question);
2063
                        } else {
2064
                            question.setQuizUuid( quiz.getUuid());
2065
                            question.setText( objQuestion.getString("text"));
2066
                            question.setType( objQuestion.getString("type"));
2067
                            question.setPoints( objQuestion.getInt("points"));
2068
                            question.setMaxlength( objQuestion.getInt("maxlength"));
2069
 
2070
                            questionDao.update(question);
2071
                        }
2072
 
2073
 
2074
 
2075
 
1 gabriel 2076
                        arrayAnswers = objQuestion.getJSONArray("answers");
2077
                        for (x = 0; x < arrayAnswers.length(); x++) {
2078
                            objAnswer = arrayAnswers.getJSONObject(x);
2079
 
19 gabriel 2080
                            uuid = objAnswer.getString("uuid");
2081
                            answer = answerDao.selectByUuid(uuid);
1 gabriel 2082
 
19 gabriel 2083
                            if(answer == null) {
1 gabriel 2084
 
19 gabriel 2085
                                answer = new Answer();
2086
                                answer.setQuestionUuid(question.getUuid());
2087
                                answer.setUuid(uuid);
2088
                                answer.setText(objAnswer.getString("text"));
2089
                                answer.setPoints(objAnswer.getInt("points"));
2090
                                answer.setCorrect(objAnswer.getString("correct"));
2091
 
2092
                                answerDao.insert(answer);
2093
                            } else {
2094
                                answer.setQuestionUuid(question.getUuid());
2095
                                answer.setText(objAnswer.getString("text"));
2096
                                answer.setPoints(objAnswer.getInt("points"));
2097
                                answer.setCorrect(objAnswer.getString("correct"));
2098
                                answerDao.update(answer);
2099
                            }
2100
                        }
1 gabriel 2101
                    }
2102
                }
2103
            }
2104
 
2105
 
2106
 
2107
 
2108
 
2109
            if(data.has("topics")) {
19 gabriel 2110
                Topic topic;
2111
                Capsule capsule;
2112
                Slide slide;
1 gabriel 2113
 
2114
                JSONArray arrayTopics = data.getJSONArray("topics");
2115
                for (i = 0; i < arrayTopics.length(); i++) {
2116
                    objTopic = arrayTopics.getJSONObject(i);
2117
 
19 gabriel 2118
                    uuid = objTopic.getString("company_uuid");
2119
                    company = companyDao.selectByUuid(uuid);
1 gabriel 2120
                    if (company == null) {
2121
                        company = new Company();
2122
                        company.setUuid(objTopic.getString("company_uuid"));
2123
                        company.setName(objTopic.getString("company_name"));
2124
                        company.setImage(objTopic.getString("company_image"));
2125
 
2126
                        companyDao.insert(company);
19 gabriel 2127
                    } else {
2128
                        company.setName(objTopic.getString("company_name"));
2129
                        company.setImage(objTopic.getString("company_image"));
2130
 
2131
                        companyDao.update(company);
1 gabriel 2132
                    }
2133
 
19 gabriel 2134
                    uuid = objTopic.getString("uuid");
2135
                    topic = topicDao.selectByUuid(uuid);
1 gabriel 2136
 
19 gabriel 2137
                    if (topic == null) {
2138
                        topic = new Topic();
2139
                        topic.setUuid(uuid);
2140
                        topic.setCompanyUuid(company.getUuid());
2141
                        topic.setName(objTopic.getString("name"));
2142
                        topic.setDescription(objTopic.getString("description"));
2143
                        topic.setImage(objTopic.getString("image"));
2144
                        topic.setPosition(objTopic.getInt("position"));
2145
                        topicDao.insert(topic);
2146
                    } else {
2147
                        topic.setCompanyUuid(company.getUuid());
2148
                        topic.setName(objTopic.getString("name"));
2149
                        topic.setDescription(objTopic.getString("description"));
2150
                        topic.setImage(objTopic.getString("image"));
2151
                        topic.setPosition(objTopic.getInt("position"));
2152
                        topicDao.update(topic);
2153
                    }
2154
 
2155
 
2156
 
2157
 
2158
 
1 gabriel 2159
                    arrayCapsules = objTopic.getJSONArray("capsules");
27 gabriel 2160
                  //  Log.e("Objeto:",""+objTopic.getJSONArray("capsules"));
21 gabriel 2161
 
1 gabriel 2162
                    for (j = 0; j < arrayCapsules.length(); j++) {
2163
                        objCapsule = arrayCapsules.getJSONObject(j);
19 gabriel 2164
                        uuid = objCapsule.getString("uuid");
2165
                        capsule = capsuleDao.selectByUuid(uuid);
2166
                        if(capsule == null) {
2167
                            capsule = new Capsule();
2168
                            capsule.setTopicUuid(topic.getUuid());
2169
                            capsule.setUuid(uuid);
2170
                            capsule.setName(objCapsule.getString("name"));
2171
                            capsule.setDescription(objCapsule.getString("description"));
2172
                            capsule.setImage(objCapsule.getString("image"));
2173
                            capsule.setPosition(objCapsule.getInt("position"));
21 gabriel 2174
                            capsule.setAddedOn(objCapsule.getString("added_on"));
2175
                            capsule.setUpdatedOn(objCapsule.getString("updated_on"));
23 gabriel 2176
                           // Log.e("Capsula ","added on"+objCapsule.getString("added_on"));
19 gabriel 2177
                            capsuleDao.insert(capsule);
2178
                        } else {
2179
                            capsule = new Capsule();
2180
                            capsule.setTopicUuid(topic.getUuid());
2181
                            capsule.setName(objCapsule.getString("name"));
2182
                            capsule.setDescription(objCapsule.getString("description"));
2183
                            capsule.setImage(objCapsule.getString("image"));
2184
                            capsule.setPosition(objCapsule.getInt("position"));
21 gabriel 2185
                            capsule.setAddedOn(objCapsule.getString("added_on"));
2186
                            capsule.setUpdatedOn(objCapsule.getString("updated_on"));
23 gabriel 2187
                           // Log.e("Capsula ","added on"+objCapsule.getString("added_on"));
19 gabriel 2188
                            capsuleDao.update(capsule);
2189
                        }
1 gabriel 2190
 
19 gabriel 2191
 
2192
 
2193
 
1 gabriel 2194
                        arraySlides = objCapsule.getJSONArray("slides");
2195
                        for (x = 0; x < arraySlides.length(); x++) {
2196
                            objSlide = arraySlides.getJSONObject(x);
2197
 
19 gabriel 2198
 
2199
                            uuid = objSlide.getString("uuid");
2200
                            slide = slideDao.selectByUuid(uuid);
2201
 
2202
                            if(slide == null) {
2203
 
2204
                                slide = new Slide();
2205
                                slide.setUuid(uuid);
2206
                                slide.setTopicUuid(capsule.getTopicUuid());
2207
                                slide.setCapsuleUuid(capsule.getUuid());
2208
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2209
                                slide.setName(objSlide.getString("name"));
2210
                                slide.setDescription(objSlide.getString("description"));
2211
                                slide.setPosition(objSlide.getInt("position"));
2212
                                slide.setType(objSlide.getString("type"));
2213
                                slide.setFile(objSlide.getString("file"));
2214
                                slide.setBackground(objSlide.getString("background"));
2215
 
2216
                                slideDao.insert(slide);
2217
                            } else {
2218
                                slide.setTopicUuid(capsule.getTopicUuid());
2219
                                slide.setCapsuleUuid(capsule.getUuid());
2220
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2221
                                slide.setName(objSlide.getString("name"));
2222
                                slide.setDescription(objSlide.getString("description"));
2223
                                slide.setPosition(objSlide.getInt("position"));
2224
                                slide.setType(objSlide.getString("type"));
2225
                                slide.setFile(objSlide.getString("file"));
2226
                                slide.setBackground(objSlide.getString("background"));
2227
 
2228
                                slideDao.update(slide);
2229
                            }
1 gabriel 2230
                        }
2231
 
2232
                    }
2233
 
2234
 
2235
                }
2236
            }
2237
 
19 gabriel 2238
            if(data.has( "extended")) {
1 gabriel 2239
 
19 gabriel 2240
                JSONObject objExtended;
2241
                JSONObject objItem;
2242
                JSONArray objItems;
2243
 
2244
 
2245
 
2246
                UserExtended userExtended;
2247
 
2248
                JSONArray extendedCompanies = data.getJSONArray("extended");
2249
                for(i = 0 ; i < extendedCompanies.length(); i++)
2250
                {
2251
                    objExtended = extendedCompanies.getJSONObject(i);
2252
                    if(objExtended.has("details")) {
2253
                        uuid = objExtended.getString("company_uuid");
2254
 
2255
 
2256
                        company = companyDao.selectByUuid(uuid);
2257
                        if (company == null) {
2258
                            company = new Company();
2259
                            company.setUuid(objExtended.getString("company_uuid"));
2260
                            company.setName(objExtended.getString("company_name"));
2261
                            company.setImage(objExtended.getString("company_image"));
2262
 
2263
                            companyDao.insert(company);
2264
                        } else {
2265
                            company.setName(objExtended.getString("company_name"));
2266
                            company.setImage(objExtended.getString("company_image"));
2267
 
2268
                            companyDao.update(company);
2269
                        }
2270
 
2271
                        objItems = objExtended.getJSONArray("details");
2272
                        for(j = 0 ; j < objItems.length(); j++) {
2273
                            objItem = objItems.getJSONObject(j);
2274
 
2275
                            uuid =  objItem.getString("uuid");
2276
 
2277
                            userExtended = userExtendedDao.selectByUuid(uuid);
2278
                            if(userExtended == null) {
2279
                                userExtended = new UserExtended();
2280
                                userExtended.setCompanyUuid(company.getUuid());
2281
                                userExtended.setUuid(uuid);
2282
                                userExtended.setLabel(objItem.getString("label"));
2283
                                userExtended.setValue(objItem.getString("value"));
2284
                                userExtendedDao.insert(userExtended);
2285
                            } else {
2286
                                userExtended.setCompanyUuid(company.getUuid());
2287
                                userExtended.setLabel(objItem.getString("label"));
2288
                                userExtended.setValue(objItem.getString("value"));
2289
                                userExtendedDao.update(userExtended);
2290
                            }
2291
 
2292
 
2293
 
2294
 
2295
                        }
2296
                    }
2297
                }
2298
 
2299
            }
2300
 
2301
 
1 gabriel 2302
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2303
            if(data.has("max_date_changes")) {
2304
                String max_date_changes = data.getString("max_date_changes");
2305
                Log.d("syncFromServer", "max_date_changes : " + max_date_changes);
2306
 
2307
                if(!TextUtils.isEmpty(max_date_changes)) {
2308
                    preference.setMaxDateChanges(max_date_changes);
2309
                }
2310
            } else {
2311
                Log.d("syncFromServer", "No max_date_changes");
2312
            }
2313
 
2314
            Calendar calendar = Calendar.getInstance();
2315
            Date date = calendar.getTime();
2316
 
2317
            String  addedOn = simpleDateFormat.format(date);
2318
 
2319
            List<Company> companies = mAppDatabase.getCompanyDao().selectAll();
2320
            int companySize = companies.size();
2321
 
2322
            if(companySize > 0) {
2323
 
2324
                if(TextUtils.isEmpty(preference.getCompanyUuidActive())) {
2325
 
2326
                    preference.setCompanyUuidActive(companies.get(0).getUuid());
2327
 
2328
                } else {
2329
 
2330
                    boolean companyExist = false;
19 gabriel 2331
                    for(i = 0; i < companies.size(); i++) {
2332
 
2333
                        if (companies.get(i).getUuid().equals(preference.getCompanyUuidActive())) {
1 gabriel 2334
                            companyExist = true;
19 gabriel 2335
                            break;
1 gabriel 2336
                        }
2337
                    }
2338
 
19 gabriel 2339
                    if(!companyExist && companies.size() > 0) {
1 gabriel 2340
                        preference.setCompanyUuidActive(companies.get(0).getUuid());
2341
                    }
2342
                }
2343
 
2344
            } else {
2345
                preference.setCompanyUuidActive("");
2346
            }
2347
 
2348
 
2349
 
2350
            preference.setLastDataRefresh(addedOn);
2351
            preference.setCompanyCount(companySize);
3 gabriel 2352
            preference.save();
1 gabriel 2353
 
2354
        } catch (JSONException e) {
2355
            Log.d(TAG, e.getMessage());
2356
        }
2357
    }
2358
 
2359
    @Override
2360
    public void requestExecuteSyncAdapter() {
2361
            // Pass the settings flags by inserting them in a bundle
2362
            Bundle settingsBundle = new Bundle();
2363
            settingsBundle.putBoolean(
2364
                    ContentResolver.SYNC_EXTRAS_MANUAL, true);
2365
            settingsBundle.putBoolean(
2366
                    ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
2367
 
2368
            ContentResolver.requestSync(mAccount, Constants.AUTHORITY, settingsBundle);
2369
    }
2370
 
2371
 
2372
    private void processResponseServerChanges(String dataString)
2373
    {
2374
 
2375
        Log.d(TAG, "processResponseServerChanges = " + dataString);
2376
 
2377
        try {
2378
            JSONObject objJSON = new JSONObject(dataString);
2379
            boolean success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2380
 
2381
 
2382
            if(success) {
2383
                Calendar calendar = Calendar.getInstance();
2384
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2385
                preference.setLastDataRefresh(simpleDateFormat.format(calendar.getTime()));
3 gabriel 2386
                preference.save();
1 gabriel 2387
 
2388
                String max_date_changes = "";
2389
                boolean processChanges = false;
2390
 
2391
                JSONObject data = objJSON.getJSONObject("data");
11 gabriel 2392
 
2393
 
1 gabriel 2394
                if(data.has("max_date_changes") && data.has("new_capsules")) {
2395
                    int new_capsules = data.getInt("new_capsules");
2396
                    max_date_changes = data.getString("max_date_changes");
2397
 
2398
 
2399
 
2400
 
2401
                    processChanges = new_capsules > 0 && !max_date_changes.equals(preference.getMaxDateChanges());
2402
                } else {
2403
                    processChanges = false;
2404
                }
2405
 
2406
                if(processChanges && !max_date_changes.isEmpty()) {
2407
                    int new_capsules = data.getInt("new_capsules");
2408
                    String message = new_capsules == 1
25 gabriel 2409
                            ? "Hay 1 cápsula disponible"
1 gabriel 2410
                            : "Hay " + new_capsules + " cápsulas disponible";
2411
 
2412
 
25 gabriel 2413
 
2414
 
11 gabriel 2415
                    showMessageSnackBarWithClose(message);
1 gabriel 2416
 
2417
 
2418
                    preference.setMaxDateChanges(max_date_changes);
2419
 
2420
                    if(!isForeground) {
2421
                        String body = new_capsules == 1
25 gabriel 2422
                                ? "Hay 1 cápsula disponible"
1 gabriel 2423
                                : "Hay " + new_capsules + " cápsulas disponible";
44 efrain 2424
                        showFcmNotification("Nuevo contenido", body, new_capsules, "", false);
1 gabriel 2425
                    }
2426
 
2427
                    /*
2428
                    if(!isForeground) {
2429
                        String body = new_capsules == 1
2430
                                ? "Hay 1 cápsula nueva disponible"
2431
                                : "Hay " + new_capsules + " cápsulas disponible";
2432
                        showFcmNotification("Nuevo contenido", body, new_capsules);
2433
 
2434
 
2435
                        AnswerDao answerDao = mAppDatabase.getAnswerDao();
2436
                        answerDao.removeAll();
2437
 
2438
                        QuestionDao questionDao = mAppDatabase.getQuestionDao();
2439
                        questionDao.removeAll();
2440
 
2441
                        QuizDao quizDao = mAppDatabase.getQuizDao();
2442
                        quizDao.removeAll();
2443
 
2444
                        SlideDao slideDao = mAppDatabase.getSlideDao();
2445
                        slideDao.removeAll();
2446
 
2447
                        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
2448
                        capsuleDao.removeAll();
2449
 
2450
                        TopicDao topicDao = mAppDatabase.getTopicDao();
2451
                        topicDao.removeAll();
2452
 
2453
                        CompanyDao companyDao = mAppDatabase.getCompanyDao();
2454
                        companyDao.removeAll();
2455
 
2456
                        UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
2457
                        userExtendedDao.removeAll();
2458
 
2459
 
2460
                        this.syncFromServer(data);
2461
 
2462
 
2463
                        if(!TextUtils.isEmpty(preference.getSlideUuidActive())) {
2464
 
2465
                            Slide slide = mAppDatabase.getSlideDao().selectByUuid(preference.getSlideUuidActive());
2466
                            if(slide == null) {
2467
                                preference.setFragmentIdxActive(Constants.IDX_FRAGMENT_TOPICS);
2468
                                preference.save(this);
2469
                            }
2470
 
2471
                        }
2472
                    }*/
25 gabriel 2473
 
2474
 
1 gabriel 2475
                }
2476
            }
2477
        } catch (JSONException e) {
2478
            Log.d(TAG, e.getMessage());
2479
        }
2480
    }
2481
 
2482
    @Override
2483
    public AppDatabase getDatabase() {
2484
        return mAppDatabase;
2485
    }
2486
 
2487
    @Override
2488
    public void syncToServerOrCheckChanges()
2489
    {
2490
        if(TextUtils.isEmpty(preference.getDeviceUuid())) {
2491
            return;
2492
        }
2493
 
2494
        SyncDao syncDao = mAppDatabase.getSyncDao();
2495
        List<Sync> records = syncDao.selectBatch();
2496
 
2497
        if(records.size() > 0) {
2498
            syncToServer(records);
2499
        } else {
2500
 
2501
                long timeLast = 0;
2502
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2503
                if (!TextUtils.isEmpty(preference.getLastDataRefresh())) {
2504
                    try {
2505
                        timeLast = simpleDateFormat.parse(preference.getLastDataRefresh()).getTime();
2506
                    } catch (Exception e) {
2507
 
2508
                    }
2509
 
2510
                }
2511
 
2512
 
2513
                Calendar calendar = Calendar.getInstance();
2514
                long timeNow = calendar.getTime().getTime();
32 efrain 2515
 
36 gabriel 2516
                if(timeNow > (timeLast + Constants.CHECK_CHANGES_TOKEN_INTERVAL)){
2517
 
2518
                    //Procesamiento en caso que el token no este, check cada 15 minutos.
2519
 
2520
                    if(preference.isRefreshTokenIsRequired()) {
2521
                        FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
32 efrain 2522
                            @Override
2523
                            public void onComplete(@NonNull Task<String> task) {
2524
                                if (!task.isSuccessful()) {
2525
                                    Log.w(TAG, "Fetching FCM registration token failed", task.getException());
2526
                                    return;
2527
                                }
2528
 
2529
                                // Get new FCM registration token
2530
                                String token = task.getResult();
2531
 
2532
                                Log.e("BUG Token", "Token 3 :  " + token);
2533
 
2534
                                createSyncRecordNewToken(token);
2535
 
2536
                                preference.setRefreshTokenIsRequired(false);
2537
                                preference.save();
2538
                            }
2539
                        });
2540
 
2541
 
36 gabriel 2542
                    } else {
32 efrain 2543
 
36 gabriel 2544
                        if (preference.getDeviceToken().isEmpty()) {
2545
                            FirebaseMessaging.getInstance().deleteToken().addOnCompleteListener(new OnCompleteListener<Void>() {
2546
                                @Override
2547
                                public void onComplete(@NonNull Task<Void> task) {
2548
                                    preference.setRefreshTokenIsRequired(true);
2549
                                    preference.save();
32 efrain 2550
 
36 gabriel 2551
                                    Log.e("Esta vacio"," mando delete token");
32 efrain 2552
 
36 gabriel 2553
                                }
2554
                            });
2555
                        }
2556
                    }
2557
                }
32 efrain 2558
 
36 gabriel 2559
                 if (timeNow > (timeLast + Constants.CHECK_CHANGES_INTERVAL)) {
2560
                     //Solicitar revision de cambios cada 4 horas.
1 gabriel 2561
                    requestCheckChanges();
2562
                }
2563
        }
2564
    }
2565
 
2566
 
2567
 
2568
    public void syncToServer(List<Sync> records)
2569
    {
2570
 
2571
 
2572
        int maxRecordsSyncBatch = 0;
2573
        FormBody.Builder formBodyBatchBuilder = new FormBody.Builder();
2574
        formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_DEVICE_UUID, preference.getDeviceUuid());
2575
 
2576
        for(Sync record : records)
2577
        {
2578
 
27 gabriel 2579
           // Log.e("Ingreso a", "syncToServer"+record.getType()+" data"+record.getData());
2580
 
2581
          //  Log.d(TAG, "SyncRecord ID = " + record.getId() + " Data : "  + record.getData() + " Type= " + record.getType());
2582
 
28 gabriel 2583
 
1 gabriel 2584
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {
2585
                Log.d(TAG, "Device");
2586
 
36 gabriel 2587
 
1 gabriel 2588
                try {
2589
                    Http http = new Http(this.getCacheDir());
2590
                    OkHttpClient client = http.getHttpClient(false);
2591
 
2592
                    RequestBody formBody = new FormBody.Builder()
2593
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID,  String.valueOf(Configuration.APPLICATION_ID))
2594
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
2595
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
2596
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
2597
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE  + " " + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName())
2598
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
2599
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
2600
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
2601
                            .build();
2602
 
2603
                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
2604
                    Request request = new Request.Builder()
2605
                            .url(Configuration.URL_DEVICE)
2606
                            .post(formBody)
2607
                            .build();
2608
 
36 gabriel 2609
                    isSyncDevice = true;
2610
 
1 gabriel 2611
                    Call call = client.newCall(request);
2612
                    call.enqueue(new okhttp3.Callback() {
2613
                        public void onResponse(Call call, Response response)
2614
                                throws IOException {
2615
                            Log.d(TAG, "Response Device :  " +  response.body().toString());
36 gabriel 2616
                            isSyncDevice = false;
1 gabriel 2617
 
43 gabriel 2618
                            processResponseSyncToServer(response.body().string(),"device");
1 gabriel 2619
                        }
2620
 
2621
                        public void onFailure(Call call, IOException e) {
2622
                            isSyncDevice = false;
2623
                            Log.d(TAG, "Error :  " +  e.getMessage());
2624
                        }
2625
                    });
2626
                } catch (Exception e) {
2627
                }
2628
            }
2629
 
36 gabriel 2630
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken && !isSyncDevice) {
1 gabriel 2631
                isSyncToken = true;
2632
                Log.d(TAG, "FCM");
27 gabriel 2633
                Log.e("Token a Sync",""+record.getData());
1 gabriel 2634
 
2635
                try {
2636
                    Http http = new Http(this.getCacheDir());
2637
                    OkHttpClient client = http.getHttpClient(false);
2638
 
2639
                    RequestBody formBody = new FormBody.Builder()
2640
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID,preference.getDeviceUuid())
2641
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
2642
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
2643
                            .build();
2644
 
2645
                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
2646
                    Request request = new Request.Builder()
2647
                            .url(Configuration.URL_FCM)
2648
                            .post(formBody)
2649
                            .build();
2650
 
2651
                    Call call = client.newCall(request);
2652
                    call.enqueue(new okhttp3.Callback() {
2653
                        public void onResponse(Call call, Response response)
2654
                                throws IOException {
2655
                            isSyncToken = false;
27 gabriel 2656
                            Log.e("Se envio", "Procesando respuesta");
43 gabriel 2657
                            processResponseSyncToServer(response.body().string(),"");
1 gabriel 2658
                        }
2659
 
2660
                        public void onFailure(Call call, IOException e) {
2661
                            Log.d(TAG, "Error :  " +  e.getMessage());
2662
                            isSyncToken = false;
2663
                        }
2664
                    });
2665
                } catch (Exception e) {
2666
 
2667
 
2668
                }
2669
            }
2670
 
2671
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_SYNC ) {
2672
                Log.d(TAG, "SYNC BATCH");
2673
                maxRecordsSyncBatch++;
2674
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_DATA + maxRecordsSyncBatch, record.getData());
2675
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_SYNC_ID + maxRecordsSyncBatch, String.valueOf(record.getId()));
2676
            }
2677
        }
2678
 
2679
 
2680
        if(maxRecordsSyncBatch > 0 && !isSyncBatch) {
2681
            Log.d(TAG, "Sync Batch");
2682
            isSyncBatch = true;
2683
 
2684
            try {
2685
                Http http = new Http(this.getCacheDir());
2686
                OkHttpClient client = http.getHttpClient(false);
2687
 
2688
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_MAX_RECORDS, String.valueOf(maxRecordsSyncBatch));
2689
                RequestBody formBody = formBodyBatchBuilder.build();
2690
 
2691
                Log.d(TAG, "URL = " + Configuration.URL_SYNC_BATCH);
2692
                Request request = new Request.Builder()
2693
                    .url(Configuration.URL_SYNC_BATCH)
2694
                    .post(formBody)
2695
                    .build();
2696
 
2697
                Call call = client.newCall(request);
2698
                call.enqueue(new okhttp3.Callback() {
2699
                    public void onResponse(Call call, Response response) throws IOException {
2700
                        isSyncBatch = false;
32 efrain 2701
                        processResponseServerBatch(response.body().string());
1 gabriel 2702
                    }
2703
 
2704
                    public void onFailure(Call call, IOException e) {
2705
                        Log.d(TAG, "Error :  " +  e.getMessage());
2706
                        isSyncBatch = false;
2707
                    }
2708
                });
2709
            } catch (Exception e) {
2710
 
2711
 
2712
            }
2713
        }
2714
 
2715
 
2716
    }
2717
 
32 efrain 2718
    private void processResponseServerBatch(String dataString)
1 gabriel 2719
    {
2720
        boolean success = false;
2721
        long sync_id = 0;
2722
 
2723
        Log.d(TAG, "processResponseServer = " + dataString);
2724
        try {
2725
            JSONObject objJSON = new JSONObject(dataString);
2726
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2727
            if(success  && objJSON.has("data")) {
2728
                JSONArray jsonArrayData = objJSON.getJSONArray("data");
2729
 
2730
 
2731
                JSONObject jsonObjectData;
2732
                int max = jsonArrayData.length();
2733
                for(int i = 0; i < max; i++) {
2734
                    jsonObjectData = jsonArrayData.getJSONObject(i);
2735
 
2736
                    if(jsonObjectData.has("success") && jsonObjectData.getBoolean("success")) {
2737
                        sync_id = jsonObjectData.getLong("sync_id");
2738
 
2739
                        mAppDatabase.getSyncDao().remove(sync_id);
2740
 
2741
                    }
2742
 
2743
 
2744
                }
2745
 
2746
                /*
2747
                if(jsonObjectData.has("message")) {
2748
                    message = jsonObjectData.getString("message");
2749
                }
2750
 
2751
                if(jsonObjectData.has("aes")) {
2752
                    preference.setAes(jsonObjectData.getString("aes"));
2753
                    preference.save(this);
2754
                }
2755
 
2756
                if(jsonObjectData.has("password")) {
2757
                    preference.setPassword(jsonObjectData.getString("password"));
2758
                    preference.save(this);
2759
                }
2760
                */
2761
            }
2762
            if(success && sync_id > 0) {
2763
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2764
                mAppDatabase.getSyncDao().remove(sync_id);
28 gabriel 2765
 
1 gabriel 2766
            }
2767
        } catch (JSONException e) {
2768
            e.printStackTrace();
2769
        }
2770
    }
2771
 
43 gabriel 2772
    private void processResponseSyncToServer(String dataString, String origen)
1 gabriel 2773
    {
2774
        boolean success = false;
2775
        long sync_id = 0;
2776
 
2777
        Log.d(TAG, "processResponseServer = " + dataString);
2778
        try {
2779
            JSONObject objJSON = new JSONObject(dataString);
2780
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2781
            if(success  && objJSON.has("data")) {
2782
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
2783
 
32 efrain 2784
 
1 gabriel 2785
                if(jsonObjectData.has("sync_id")) {
2786
                    sync_id = jsonObjectData.getLong("sync_id");
2787
                }
2788
 
2789
                /*
2790
                if(jsonObjectData.has("message")) {
2791
                    message = jsonObjectData.getString("message");
2792
                }
2793
 
2794
                if(jsonObjectData.has("aes")) {
2795
                    preference.setAes(jsonObjectData.getString("aes"));
2796
                    preference.save(this);
2797
                }
2798
 
2799
                if(jsonObjectData.has("password")) {
2800
                    preference.setPassword(jsonObjectData.getString("password"));
2801
                    preference.save(this);
2802
                }
2803
                */
2804
            }
2805
            Log.d(TAG, "SyncID = " + sync_id);
2806
            if(success && sync_id > 0) {
2807
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2808
                mAppDatabase.getSyncDao().remove(sync_id);
43 gabriel 2809
 
2810
                if(origen.equals("device"))
2811
                {
2812
                    syncToServerOrCheckChanges();
2813
 
2814
                }
1 gabriel 2815
            }
2816
        } catch (JSONException e) {
2817
            e.printStackTrace();
2818
        }
2819
    }
2820
 
32 efrain 2821
    /*
27 gabriel 2822
    private void processResponseSyncTokenFCMtoServer(String dataString)
2823
    {
2824
        Log.e("Respuesta",""+dataString);
2825
        boolean success = false;
2826
 
2827
        try {
2828
            JSONObject objJSON = new JSONObject(dataString);
2829
            success = objJSON.has("success") && objJSON.getBoolean("success");
2830
 
2831
            if(success) {
2832
                Log.e("Token almacenado"," en server de manera exitosa");
2833
            }
2834
        } catch (JSONException e) {
2835
            e.printStackTrace();
2836
        }
2837
    }
2838
 
2839
 
32 efrain 2840
     */
27 gabriel 2841
 
32 efrain 2842
 
1 gabriel 2843
    /*
2844
    private void processResponseServerCheckChanges(String dataString) {
2845
 
2846
        Log.d(TAG, "processResponseServerCheckChanges = " + dataString);
2847
 
2848
        runOnUiThread(new Runnable() {
2849
 
2850
            @Override
2851
            public void run() {
2852
 
2853
                try {
2854
                    JSONObject objJSON = new JSONObject(dataString);
2855
                    boolean success = objJSON.has("success") ? objJSON.getBoolean("success") : false;
2856
                    String message = "";
2857
                    if (objJSON.has("data")) {
2858
                        Object item = objJSON.get("data");
2859
                        if (item instanceof String) {
2860
                            message = item.toString();
2861
                        }
2862
                    }
2863
 
2864
                    if (success) {
2865
                        mAppDatabase.getAnswerDao().removeAll();
2866
                        mAppDatabase.getQuestionDao().removeAll();
2867
                        mAppDatabase.getQuizDao().removeAll();
2868
                        mAppDatabase.getSlideDao().removeAll();
2869
                        mAppDatabase.getCapsuleDao().removeAll();
2870
                        mAppDatabase.getTopicDao().removeAll();
2871
 
2872
 
2873
                        JSONObject data = objJSON.getJSONObject("data");
2874
                        syncFromServer(data);
2875
 
2876
 
2877
                    }
2878
 
2879
 
2880
                } catch (JSONException e) {
2881
                    Log.d(TAG, e.getMessage());
2882
                }
2883
 
2884
                reloadNavHeader();
2885
 
2886
 
2887
            }
2888
        });
2889
    }
2890
     */
2891
 
49 gabriel 2892
    private void processResponseServer(String dataString) {
1 gabriel 2893
 
49 gabriel 2894
        Log.d(TAG, "processResponseServer = " + dataString);
1 gabriel 2895
 
49 gabriel 2896
        runOnUiThread(new Runnable() {
2897
 
2898
            @Override
2899
            public void run() {
2900
 
2901
                try {
2902
                    JSONObject objJSON = new JSONObject(dataString);
2903
                    boolean success = objJSON.has("success") ? objJSON.getBoolean("success") : false;
2904
                    String message = "";
2905
                    if (objJSON.has("data")) {
2906
                        Object item = objJSON.get("data");
2907
                        if (item instanceof String) {
2908
                            message = item.toString();
2909
                        }
2910
                    }
2911
 
2912
                    if (success) {
2913
 
2914
                        getDatabase().getAnswerDao().removeAll();
2915
                        getDatabase().getQuestionDao().removeAll();
2916
                        getDatabase().getQuizDao().removeAll();
2917
                        getDatabase().getSlideDao().removeAll();
2918
                        getDatabase().getCapsuleDao().removeAll();
2919
                        getDatabase().getTopicDao().removeAll();
2920
                        getDatabase().getUserExtendedDao().removeAll();
2921
                        getDatabase().getUserLogDao().removeAllUserUuidNotEqual(preference.getUserUuid());
2922
                        getDatabase().getProgressDao().removeAllUserUuidNotEqual(preference.getUserUuid());
2923
 
2924
                        JSONObject data = objJSON.getJSONObject("data");
2925
                        syncFromServer(data);
2926
 
2927
                        preference.setRefreshContentRequired(false);
2928
                        Toast.makeText(getApplicationContext(), "¡Contenido actualizado con exito!", Toast.LENGTH_SHORT).show();
2929
 
2930
                    } else {
2931
                       showMessageSnackBar(message);
2932
                    }
2933
 
2934
 
2935
                } catch (JSONException e) {
2936
                    Log.d(TAG, e.getMessage());
2937
                }
2938
 
2939
 
2940
            }
2941
        });
2942
 
2943
 
2944
    }
2945
 
19 gabriel 2946
}