Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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