Proyectos de Subversion Android Microlearning

Rev

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

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