Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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