Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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