Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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