Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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