Proyectos de Subversion Android Microlearning

Rev

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

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