Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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