Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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

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