Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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