Proyectos de Subversion Android Microlearning

Rev

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

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