Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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