Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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