Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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