Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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