Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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