Proyectos de Subversion Android Microlearning

Rev

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