Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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