Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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