Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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