Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 33 | Rev 35 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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