Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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