Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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