Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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