Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 19 | Rev 21 | 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
                if(preference.getOrigenNavigation().equals("welcome"))
678
                {
679
                    preference.setOrigennavigation("");
19 gabriel 680
                    setTitleActionBar(getString(R.string.app_name));
18 gabriel 681
                    invokeFragment(Constants.IDX_FRAGMENT_WELCOME);
682
 
683
                }
684
 
685
                break;
1 gabriel 686
            case Constants.IDX_FRAGMENT_FINISH_TOPIC :
687
 
688
                preference.setTopicUuidActive("");
689
                preference.setCapsuleUuidActive("");
690
                preference.setSlideUuidActive("");
3 gabriel 691
                preference.save();
1 gabriel 692
 
693
                invokeFragment(Constants.IDX_FRAGMENT_TOPICS);
694
                return;
695
 
696
            case Constants.IDX_FRAGMENT_SLIDES :
18 gabriel 697
 
1 gabriel 698
                invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
18 gabriel 699
 
1 gabriel 700
                return;
701
 
702
            case Constants.IDX_FRAGMENT_GALLERY :
18 gabriel 703
 
1 gabriel 704
                invokeFragment(Constants.IDX_FRAGMENT_SLIDES);
18 gabriel 705
 
1 gabriel 706
                return;
707
 
708
            case Constants.IDX_FRAGMENT_FINISH_CAPSULE :
709
                preference.setCapsuleUuidActive("");
710
                preference.setSlideUuidActive("");
3 gabriel 711
                preference.save();
1 gabriel 712
 
713
                invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
714
                return;
715
 
716
        }
717
    }
718
 
719
 
720
 
721
    @Override
722
    public void hideProgressBar() {
723
 
724
        //accessing it from ui-thread
725
        runOnUiThread(new Runnable() {
726
            @Override
727
            public void run() {
728
                mProgressBar.setVisibility(View.INVISIBLE);
729
            }
730
        });
731
 
732
    }
733
 
734
    @Override
735
    public void showProgressBar() {
736
        runOnUiThread(new Runnable() {
737
            @Override
738
            public void run() {
739
                mProgressBar.setVisibility(View.VISIBLE);
740
            }
741
        });
742
 
743
 
744
    }
745
 
8 gabriel 746
    @Override
747
    public void hideNavigationAndtoolbar() {
1 gabriel 748
 
8 gabriel 749
        Log.e("Ocultar"," Navigation and Toolbar");
750
        //accessing it from ui-thread
751
        runOnUiThread(() -> {
752
            mNavigationView.setVisibility(View.GONE);
753
            mToolbar.setVisibility(View.GONE);
754
        });
1 gabriel 755
 
8 gabriel 756
    }
1 gabriel 757
 
8 gabriel 758
    @Override
759
    public void showNavigationAndToolbar() {
760
        runOnUiThread(new Runnable() {
761
            @Override
762
            public void run() {
763
                mNavigationView.setVisibility(View.VISIBLE);
764
                mToolbar.setVisibility(View.VISIBLE);
765
            }
766
        });
1 gabriel 767
 
8 gabriel 768
 
769
    }
770
 
771
 
1 gabriel 772
    @Override
773
    public boolean onCreateOptionsMenu(Menu menu) {
774
        // Inflate the menu; this adds items to the action bar if it is present.
775
        getMenuInflater().inflate(R.menu.drawer, menu);
776
        return true;
777
    }
778
 
779
 
780
 
781
 
782
      /**
783
         * Create a new dummy account for the sync adapter
784
         *
785
         * @param context The application context
786
         */
787
    public static Account CreateSyncAccount(Context context) {
788
        // Create the account type and default account
789
        Account newAccount = new Account(
790
                Constants.ACCOUNT, Constants.ACCOUNT_TYPE);
791
        // Get an instance of the Android account manager
792
        AccountManager accountManager =
793
                (AccountManager) context.getSystemService(
794
                        ACCOUNT_SERVICE);
795
        /*
796
         * Add the account and account type, no password or user data
797
         * If successful, return the Account object, otherwise report an error.
798
         */
799
        if (accountManager.addAccountExplicitly(newAccount, null, null)) {
800
            /*
801
             * If you don't set android:syncable="true" in
802
             * in your <provider> element in the manifest,
803
             * then call context.setIsSyncable(account, AUTHORITY, 1)
804
             * here.
805
             */
806
 
807
            ContentResolver.setIsSyncable(newAccount, Constants.AUTHORITY, 1);
808
            ContentResolver.setSyncAutomatically(newAccount, Constants.AUTHORITY, true);
809
            ContentResolver.addPeriodicSync(newAccount,
810
                    Constants.AUTHORITY,  Bundle.EMPTY, Constants.SYNC_INTERVAL);
811
 
812
 
813
        } else {
814
            /*
815
             * The account exists or some other error occurred. Log this, report it,
816
             * or handle it internally.
817
             */
818
 
819
            Account[] accounts = accountManager.getAccounts();
820
            if(accounts != null && accounts.length > 0) {
821
 
822
                for(Account account : accounts)
823
                {
824
                    if(account.type.equals(Constants.ACCOUNT_TYPE)) {
825
                        return account;
826
                    }
827
                }
828
                return accounts[0];
829
            } else {
830
                return null;
831
            }
832
 
833
 
834
 
835
        }
836
 
837
        return newAccount;
838
 
839
 
840
    }
841
 
842
 
843
 
844
 
845
 
846
    @Override
847
    public void createSyncRecordNewToken(String token)
848
    {
849
 
850
        preference.setDeviceToken (token);
3 gabriel 851
        preference.save();
1 gabriel 852
 
853
        if(!TextUtils.isEmpty(preference.getDeviceUuid())) {
854
            Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, token);
855
            mAppDatabase.getSyncDao().insert(sync);
856
        }
857
    }
858
 
859
 
860
 
861
 
862
    @Override
863
    public void executeFcmCommand(String command)
864
    {
865
 
866
        if (command.equals("signout")) {
867
            signout();
868
        }
869
    }
870
 
871
 
872
 
873
    @Override
874
    public void setConnectedInternet(Boolean isConnected)
875
    {
876
        connected = isConnected;
877
        textViewMessageNotConnection.setVisibility(isConnected ? View.INVISIBLE : View.VISIBLE);
878
    }
879
 
880
    @Override
881
    public boolean isConnectedInternet() {
882
        return connected;
883
    }
884
 
885
    @Override
886
    public void showMessageSnackBar(String message) {
887
        Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_LONG).show();
888
    }
889
 
890
 
891
    @Override
892
    public void showMessageSnackBarWithClose(String message) {
11 gabriel 893
 
16 gabriel 894
    //    Log.e("Mensaje","Notificacion"+message);
11 gabriel 895
 
896
        //Crear notificacion local
897
 
898
        Calendar calendar = Calendar.getInstance();
899
        Date date = calendar.getTime();
900
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
901
        String  dateOn = simpleDateFormat.format(date);
902
 
903
        NotificationCenterDao notificacionDao =  mAppDatabase.getNotificationCenterDao();
904
        com.cesams.twogetskills.entity.NotificationCenter notificacionueva;
905
 
906
        notificacionueva = new com.cesams.twogetskills.entity.NotificationCenter();
907
 
908
        notificacionueva.setTitle("Nuevo contenido disponible");
909
        notificacionueva.setDate(dateOn);
910
        notificacionueva.setDescription(message);
911
        Log.e("Notificacion","a guardar"+notificacionueva);
912
        notificacionDao.insert(notificacionueva);
913
 
1 gabriel 914
        final Snackbar snackBar = Snackbar.make(this.findViewById(R.id.fragment_container), message, Snackbar.LENGTH_INDEFINITE);
915
 
916
        snackBar.setAction(R.string.snackbar_close, new View.OnClickListener() {
917
            @Override
918
            public void onClick(View v) {
919
                // Call your action method here
920
                snackBar.dismiss();
921
            }
922
        });
11 gabriel 923
       snackBar.show();
1 gabriel 924
 
925
 
926
    }
927
 
928
    @Override
929
    public void onErrorFatal() {
930
 
931
 
932
        invokeFragment(Constants.IDX_FRAGMENT_SIGNIN);
933
    }
934
 
935
    @Override
936
    public void invokeFragment(int fragmentIdxActiveNuevo)
937
    {
8 gabriel 938
        Log.e("Invoco fragmento"," "+fragmentIdxActiveNuevo);
939
 
1 gabriel 940
        String fragmentKeyActual    = PREFIX_FRAG + preference.getFragmentIdxActive();
941
        String fragmentKeyNuevo 	= PREFIX_FRAG + fragmentIdxActiveNuevo;
942
        preference.setFragmentIdxActive(fragmentIdxActiveNuevo);
3 gabriel 943
        preference.save();
1 gabriel 944
 
945
        Fragment fragment;
946
        if(!fragmentKeyActual.equalsIgnoreCase(fragmentKeyNuevo)) {
947
            if(fragmentHashMap.containsKey(fragmentKeyActual)) {
948
                fragment = fragmentHashMap.get(fragmentKeyActual);
949
                if(fragment != null) {
950
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
951
                    fragmentTransaction.hide(fragment);
3 gabriel 952
                    fragmentTransaction.commitAllowingStateLoss();
1 gabriel 953
                }
954
            }
955
        }
956
 
957
        boolean add = false;
958
        fragment = null;
8 gabriel 959
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
7 gabriel 960
      //  mDrawerToggle.setDrawerIndicatorEnabled(false);
1 gabriel 961
 
962
 
963
        switch(fragmentIdxActiveNuevo) {
964
            case Constants.IDX_FRAGMENT_SIGNIN :
7 gabriel 965
               // getSupportActionBar().hide();
1 gabriel 966
                 if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
967
                     fragment = fragmentHashMap.get(fragmentKeyNuevo);
968
                 } else {
969
                     add = true;
970
                     fragment = new SigninFragment();
971
                 }
972
                break;
973
 
974
            case Constants.IDX_FRAGMENT_TOPICS :
975
 
7 gabriel 976
               // getSupportActionBar().show();
977
             //   mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 978
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
979
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
980
                } else {
981
                    add = true;
8 gabriel 982
                    fragment = new TopicFragment();
1 gabriel 983
                }
984
                break;
985
 
9 gabriel 986
            case Constants.IDX_FRAGMENT_NOTIFICATION:
1 gabriel 987
 
9 gabriel 988
                // getSupportActionBar().show();
989
                //   mDrawerToggle.setDrawerIndicatorEnabled(true);
990
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
991
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
992
                } else {
993
                    add = true;
994
                    fragment = new NotificationCenter();
995
                }
996
                break;
997
 
998
 
1 gabriel 999
            case Constants.IDX_FRAGMENT_CAPSULES :
7 gabriel 1000
              //  getSupportActionBar().show();
1001
              //  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1 gabriel 1002
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1003
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1004
                } else {
1005
                    add = true;
1006
                    fragment = new CapsuleFragment();
1007
                }
1008
                break;
1009
 
1010
            case Constants.IDX_FRAGMENT_SLIDES :
7 gabriel 1011
             //   getSupportActionBar().show();
1012
             //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1 gabriel 1013
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1014
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1015
                } else {
1016
                    add = true;
1017
                    fragment = new SlideFragment();
1018
                }
1019
                break;
1020
 
1021
            case Constants.IDX_FRAGMENT_GALLERY :
7 gabriel 1022
             //   getSupportActionBar().show();
1023
             //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
1 gabriel 1024
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1025
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1026
                } else {
1027
                    add = true;
1028
                    fragment = new GalleryFragment();
1029
                }
1030
 
1031
                break;
1032
 
1033
            case Constants.IDX_FRAGMENT_FINISH_CAPSULE :
7 gabriel 1034
              //  getSupportActionBar().hide();
1 gabriel 1035
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1036
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1037
                } else {
1038
                    add = true;
1039
                    fragment = new FinishCapsuleFragment();
1040
                }
1041
                break;
1042
 
1043
            case Constants.IDX_FRAGMENT_FINISH_TOPIC :
7 gabriel 1044
              //  getSupportActionBar().hide();
1 gabriel 1045
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1046
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1047
                } else {
1048
                    add = true;
1049
                    fragment = new FinishTopicFragment();
1050
                }
1051
                break;
1052
 
1053
            case Constants.IDX_FRAGMENT_TIMELINE :
7 gabriel 1054
              //  getSupportActionBar().show();
1055
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1056
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1057
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1058
                } else {
1059
                    add = true;
1060
                    fragment = new TimelineFragment();
1061
                }
1062
                break;
1063
 
1064
            case Constants.IDX_FRAGMENT_COMPANIES:
7 gabriel 1065
              //  getSupportActionBar().show();
1066
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1067
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1068
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1069
                } else {
1070
                    add = true;
1071
                    fragment = new CompanyFragment();
1072
                }
1073
                break;
1074
 
1075
            case Constants.IDX_FRAGMENT_PROGRESS :
7 gabriel 1076
               // getSupportActionBar().show();
1077
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1078
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1079
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1080
                } else {
1081
                    add = true;
1082
                    fragment = new ProgressFragment();
1083
                }
1084
                break;
1085
 
1086
            case Constants.IDX_FRAGMENT_USER_PROFILE:
7 gabriel 1087
               // getSupportActionBar().show();
1088
              //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1 gabriel 1089
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1090
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1091
                } else {
1092
                    add = true;
1093
                    fragment = new UserProfileFragment();
1094
                }
1095
                break;
1096
 
8 gabriel 1097
            case Constants.IDX_FRAGMENT_WELCOME:
1098
                // getSupportActionBar().show();
1099
                //  mDrawerToggle.setDrawerIndicatorEnabled(true);
1100
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1101
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1102
                } else {
1103
                    add = true;
1104
                    fragment = new WelcomeFragment();
1105
                    Log.e("Vete"," a welcome");
1106
                }
1107
                break;
1108
 
1 gabriel 1109
            default :
7 gabriel 1110
               // getSupportActionBar().hide();
1 gabriel 1111
                if(fragmentHashMap.containsKey(fragmentKeyNuevo)) {
1112
                    fragment = fragmentHashMap.get(fragmentKeyNuevo);
1113
                } else {
1114
                    add = true;
1115
                    fragment = new IntroFragment();
1116
                }
1117
                break;
1118
 
1119
 
1120
        }
1121
 
1122
        if(add) {
1123
            fragmentHashMap.put(fragmentKeyNuevo, fragment);
1124
 
1125
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
1126
            fragmentTransaction.add(R.id.fragment_container, fragment, fragmentKeyNuevo);
3 gabriel 1127
            fragmentTransaction.commitAllowingStateLoss();
1 gabriel 1128
        }
1129
 
1130
 
1131
        if(fragment != null) {
1132
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
1133
            fragmentTransaction.show(fragment);
3 gabriel 1134
            fragmentTransaction.commitAllowingStateLoss();
1 gabriel 1135
        }
1136
 
1137
    }
1138
 
1139
    @Override
1140
    public void changeTopicActive(String topicUuid)
1141
    {
1142
        Log.d(TAG, "changeTopicActive : " + topicUuid);
3 gabriel 1143
       // Log.e("Guardo", "Topico en Main");
1 gabriel 1144
 
1145
        preference.setTopicUuidActive(topicUuid);
1146
        preference.setCapsuleUuidActive("");
1147
        preference.setSlideUuidActive("");
3 gabriel 1148
        preference.save();
1 gabriel 1149
 
1150
        invokeFragment(Constants.IDX_FRAGMENT_CAPSULES);
1151
    }
1152
 
1153
    @Override
1154
    public void changeCapsuleActive(String capsuleUuid)
1155
    {
1156
        Log.d(TAG, "changeCapsuleActive : " + capsuleUuid);
1157
 
1158
 
1159
 
1160
        preference.setCapsuleUuidActive(capsuleUuid);
1161
        preference.setSlideUuidActive("");
3 gabriel 1162
        preference.save();
1 gabriel 1163
 
1164
        invokeFragment(Constants.IDX_FRAGMENT_SLIDES);
1165
    }
1166
 
1167
    @Override
1168
    public void changeCompanyActive(String companyUuid)
1169
    {
1170
        Log.d(TAG, "changeCompanyActive : " + companyUuid);
1171
 
1172
        preference.setCompanyUuidActive(companyUuid);
3 gabriel 1173
        preference.save();
1 gabriel 1174
    }
1175
 
1176
    @Override
19 gabriel 1177
    public synchronized void changeSlideActive(String slideUuid, String type, boolean showGallery)
1 gabriel 1178
    {
1179
 
1180
        Log.d(TAG, "changeSlideActive : " + slideUuid);
1181
 
1182
        if(!preference.getSlideUuidActive().equals(slideUuid) && type.equals(Constants.SLIDE_TYPE_IMAGE)) {
1183
            Log.d(TAG, "registerOnPageChangeCallback - createProgressAndSyncRecord");
1184
 
1185
            createProgressAndSyncRecord(slideUuid, true, false, false);
1186
        }
1187
        preference.setSlideUuidActive(slideUuid);
3 gabriel 1188
        preference.save();
1 gabriel 1189
 
1190
 
1191
        if(showGallery) {
1192
            invokeFragment(Constants.IDX_FRAGMENT_GALLERY);
3 gabriel 1193
 
1 gabriel 1194
        }
1195
    }
1196
 
1197
    @Override
1198
    public String getTopicUuidActive()
1199
    {
1200
        return preference.getTopicUuidActive();
1201
    }
1202
 
1203
    @Override
1204
    public String getCapsuleUuidActive()
1205
    {
1206
        return preference.getCapsuleUuidActive();
1207
    }
1208
 
1209
    @Override
1210
    public String getSlideUuidActive()
1211
    {
1212
        return preference.getSlideUuidActive();
1213
    }
1214
 
1215
    @Override
1216
    public String getCompanyUuidActive()
1217
    {
1218
        return preference.getCompanyUuidActive();
1219
    }
1220
 
1221
    @Override
1222
    public void setTitleActionBar(String title)
1223
    {
8 gabriel 1224
 
1 gabriel 1225
        getSupportActionBar().setTitle(title);
1226
    }
1227
 
1228
    @Override
1229
    public synchronized void createProgressAndSyncRecord(String slideUuid, boolean completed, boolean isQuiz, boolean isAudioOrVideo)
1230
    {
1231
        Calendar calendar = Calendar.getInstance();
1232
        Date date = calendar.getTime();
1233
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1234
        String  dateOn = simpleDateFormat.format(date);
1235
 
1236
        SlideDao slideDao = mAppDatabase.getSlideDao();
1237
        Slide slide =  slideDao.selectByUuid(slideUuid);
1238
 
1239
        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1240
        Capsule capsule = capsuleDao.selectByUuid(slide.getCapsuleUuid());
1241
 
1242
        TopicDao topicDao = mAppDatabase.getTopicDao();
1243
        Topic topic = topicDao.selectByUuid(capsule.getTopicUuid());
1244
 
1245
        UserLog userLog;
1246
        UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1247
 
1248
        SyncDao syncDao = mAppDatabase.getSyncDao();
1249
        Sync sync;
1250
 
19 gabriel 1251
        String userUuid = preference.getUserUuid();
1252
 
1 gabriel 1253
        // Progreso y UserLog  del Slide
1254
        ProgressDao progressDao = mAppDatabase.getProgressDao();
19 gabriel 1255
        Progress progressSlide = progressDao.selectBySlideUuidAndUserUuid(slide.getUuid(), userUuid);
1256
        Progress progressCapsule =  progressDao.selectByCapsuleUuidAndUserUuid(slide.getCapsuleUuid(),userUuid);
1257
        Progress progressTopic =  progressDao.selectByTopicUuidAndUserUuid(slide.getTopicUuid(),userUuid);
1 gabriel 1258
 
1259
        int totalSlides = 0;
1260
        int viewSlides = 0;
1261
        double percentaje = 0;
1262
        boolean newRecord = false;
1263
        boolean retakeQuiz = false;
1264
 
1265
        /*** INICIO PROCESO DIAPOSITIVA ***/
1266
        if(progressSlide == null) {
1267
 
1268
            retakeQuiz = false;
1269
 
1270
 
1271
            progressSlide = new Progress();
1272
            progressSlide.setUserUuid(preference.getUserUuid());
1273
            progressSlide.setCompanyUuid(topic.getCompanyUuid());
1274
            progressSlide.setTopicUuid(topic.getUuid());
1275
            progressSlide.setCapsuleUuid(capsule.getUuid());
1276
            progressSlide.setSlideUuid(slide.getUuid());
1277
            progressSlide.setType(Constants.PROGERSS_TYPE_SLIDE);
1278
            progressSlide.setCompleted(completed ? 1 : 0);
1279
            progressSlide.setAddedOn(dateOn);
1280
            progressSlide.setUpdatedOn(dateOn);
1281
            progressDao.insert(progressSlide);
1282
        } else {
1283
            retakeQuiz = true;
1284
 
1285
            if (progressSlide.getCompleted() == 1) {
1286
                progressSlide.setReturningAfterCompleted(progressSlide.getReturningAfterCompleted() + 1);
1287
            } else {
1288
                if (completed) {
1289
                    //0 y 1 para Boolean
1290
                    progressSlide.setCompleted(completed  ? 1 : 0);
1291
                } else {
1292
                    progressSlide.setReturning(progressSlide.getReturning() + 1);
1293
                }
1294
            }
1295
 
1296
            progressSlide.setUpdatedOn(dateOn);
1297
            progressDao.update(progressSlide);
1298
        }
1299
 
1300
 
3 gabriel 1301
 
1 gabriel 1302
        /*** FIN PROCESO DIAPOSITIVA ***/
1303
 
1304
 
1305
 
1306
        /*** INICIO PROCESO TOPICO ***/
1307
        ResultCount resultCount;
1308
 
1309
 
1310
        resultCount = slideDao.getCountByTopicUuid(slide.getTopicUuid());
1311
        totalSlides = resultCount.getCount();
1312
 
19 gabriel 1313
        resultCount = progressDao.getCountSlidesCompletedByTopicUuidAndUserUuid(slide.getTopicUuid(), userUuid);
1 gabriel 1314
        viewSlides =  resultCount.getCount();
1315
        if(totalSlides == 0) {
1316
            percentaje = 0;
1317
        } else {
1318
            percentaje = (viewSlides * 100) / totalSlides;
1319
        }
1320
 
1321
        if(progressTopic == null) {
1322
            newRecord = true;
1323
            progressTopic = new Progress();
1324
            progressTopic.setUserUuid(preference.getUserUuid());
1325
            progressTopic.setCompanyUuid( topic.getCompanyUuid());
1326
            progressTopic.setTopicUuid (topic.getUuid());
1327
 
1328
            progressTopic.setViewSlides(viewSlides);
1329
            progressTopic.setTotalSlides(totalSlides);
1330
            progressTopic.setProgress (percentaje);
1331
            progressTopic.setType(Constants.PROGERSS_TYPE_TOPIC);
1332
 
1333
            progressTopic.setAddedOn(dateOn);
1334
            progressTopic.setUpdatedOn(dateOn);
1335
             progressDao.insert(progressTopic);
1336
        } else {
1337
            newRecord = false;
1338
            progressTopic.setViewSlides(viewSlides);
1339
            progressTopic.setTotalSlides(totalSlides);
1340
            progressTopic.setProgress (percentaje);
1341
            progressDao.update(progressTopic);
1342
        }
1343
 
1344
        try {
1345
            JSONObject json = progressTopic.toJson();
1346
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1347
 
1348
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1349
            syncDao.insert(sync);
1350
        } catch (JSONException e) {
1351
        }
1352
 
1353
        if(newRecord) {
1354
            userLog = new UserLog();
1355
            userLog.setUserUuid(preference.getUserUuid());
1356
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_TOPIC);
1357
            userLog.setCompanyUuid (topic.getCompanyUuid());
1358
            userLog.setTopicUuid (topic.getUuid());
1359
            userLog.setAddedOn(dateOn);
1360
 
1361
 
1362
            userLogDao.insert(userLog);
1363
            try {
1364
                JSONObject json = userLog.toJson();
1365
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1366
 
1367
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1368
                syncDao.insert(sync);
1369
            } catch (JSONException e) {
1370
            }
1371
        }
1372
        /*** FIN PROCESO TOPICO ***/
1373
 
1374
 
1375
 
1376
        /*** INICIO PROCESO CAPSULA ***/
1377
        resultCount = slideDao.getCountByCapsuleUuid(slide.getCapsuleUuid());
1378
        totalSlides = resultCount.getCount();
19 gabriel 1379
        resultCount = progressDao.getCountSlidesCompletedByCapsuleUuidAndUserUuid(slide.getCapsuleUuid(), userUuid);
1 gabriel 1380
        viewSlides =  resultCount.getCount();
1381
        if(totalSlides == 0) {
1382
            percentaje = 0;
1383
        } else {
1384
            percentaje = (viewSlides * 100) / totalSlides;
1385
        }
1386
 
1387
        if(progressCapsule == null) {
1388
            newRecord = true;
1389
            progressCapsule = new Progress();
1390
            progressCapsule.setUserUuid(preference.getUserUuid());
1391
            progressCapsule.setCompanyUuid(topic.getCompanyUuid());
1392
            progressCapsule.setTopicUuid(topic.getUuid());
1393
            progressCapsule.setCapsuleUuid (capsule.getUuid());
1394
            progressCapsule.setViewSlides(viewSlides);
1395
            progressCapsule.setTotalSlides(totalSlides);
1396
            progressCapsule.setProgress(percentaje);
1397
            progressCapsule.setType(Constants.PROGERSS_TYPE_CAPSULE);
1398
            progressCapsule.setAddedOn(dateOn);
1399
            progressCapsule.setUpdatedOn(dateOn);
1400
            progressDao.insert(progressCapsule);
1401
 
1402
            Log.d(TAG, "Progress Capsule Nueva : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1403
            preference.setLastCapsuleUuidActive(capsule.getUuid());
1404
        } else {
1405
            newRecord = false;
1406
            progressCapsule.setViewSlides(viewSlides);
1407
            progressCapsule.setTotalSlides(totalSlides);
1408
            progressCapsule.setProgress(percentaje);
1409
 
1410
            Log.d(TAG, "Progress Capsule : getLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1411
            Log.d(TAG, "Progress Capsule : CapsuleActive : " + preference.getCapsuleUuidActive());
1412
 
1413
            if (!preference.getLastCapsuleUuidActive().equals(preference.getCapsuleUuidActive())) {
1414
 
1415
                Log.d(TAG, "Capsule Progress : " + progressCapsule.getProgress());
1416
                Log.d(TAG, "Capsule Completed : " + progressCapsule.getCompleted());
1417
                Log.d(TAG, "Capsule Total slides : " + progressCapsule.getTotalSlides());
1418
                Log.d(TAG, "Capsule View slides : " + progressCapsule.getViewSlides());
1419
 
1420
                if(progressCapsule.getCompleted() == 1) {
1421
                    Log.d(TAG, "Capsule OLD returningAfterCompleted = " + progressCapsule.getReturningAfterCompleted());
1422
 
1423
                    int returningAfterCompleted = progressCapsule.getReturningAfterCompleted() + 1;
1424
 
1425
                    Log.d(TAG, "Capsule NEW returningAfterCompleted = " + returningAfterCompleted);
1426
                    progressCapsule.setReturningAfterCompleted(returningAfterCompleted);
1427
                }
1428
 
1429
                preference.setLastCapsuleUuidActive(capsule.getUuid());
3 gabriel 1430
                preference.save();
1 gabriel 1431
 
1432
                Log.d(TAG, "Progress Capsule : setLastCapsuleActive : " + preference.getLastCapsuleUuidActive());
1433
            }
1434
 
1435
            progressDao.update(progressCapsule);
1436
        }
1437
        try {
1438
            JSONObject json = progressCapsule.toJson();
1439
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1440
 
1441
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1442
            syncDao.insert(sync);
1443
        } catch (JSONException e) {
1444
 
1445
        }
1446
 
1447
        if(newRecord) {
1448
            userLog = new UserLog();
1449
            userLog.setUserUuid(preference.getUserUuid());
1450
            userLog.setActivity(Constants.USER_LOG_ACTIVITY_START_CAPSULE);
1451
            userLog.setCompanyUuid(topic.getCompanyUuid());
1452
            userLog.setTopicUuid(topic.getUuid());
1453
            userLog.setCapsuleUuid(capsule.getUuid());
1454
            userLog.setAddedOn(dateOn);
1455
 
1456
 
1457
            userLogDao.insert(userLog);
1458
            try {
1459
                JSONObject json = userLog.toJson();
1460
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1461
 
1462
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1463
                syncDao.insert(sync);
1464
            } catch (JSONException e) {
1465
            }
1466
        }
1467
 
1468
 
1469
        /*** FIN PROCESO CAPSULA ***/
1470
 
1471
        /*** INICIO USERLOG SLIDE ***/
1472
        userLog = new UserLog();
1473
        userLog.setUserUuid(preference.getUserUuid());
1474
        userLog.setActivity(Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1475
        userLog.setCompanyUuid(topic.getCompanyUuid());
1476
        userLog.setTopicUuid(topic.getUuid());
1477
        userLog.setCapsuleUuid(capsule.getUuid());
1478
        userLog.setSlideUuid(slide.getUuid());
1479
        userLog.setAddedOn(dateOn);
1480
 
1481
 
1482
        userLogDao.insert(userLog);
1483
        try {
1484
            JSONObject json = userLog.toJson();
1485
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1486
 
1487
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1488
            syncDao.insert(sync);
1489
        } catch (JSONException e) {
1490
        }
1491
 
1492
        /*** FIN ***/
1493
 
1494
 
1495
        /*** PROGRESS SLIDE***/
1496
        try {
1497
            JSONObject json = progressSlide.toJson();
1498
            json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_PROGRESS);
1499
 
1500
            sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1501
            syncDao.insert(sync);
1502
        } catch (JSONException e) {
1503
        }
1504
 
1505
        /** IS SLIDE = QUIZ **/
1506
        if (isQuiz) {
1507
            userLog = new UserLog();
1508
            userLog.setUserUuid(preference.getUserUuid());
1509
            userLog.setActivity(retakeQuiz ? Constants.USER_LOG_ACTIVITY_RETAKE_A_TEST : Constants.USER_LOG_ACTIVITY_TAKE_A_TEST);
1510
            userLog.setCompanyUuid (topic.getCompanyUuid());
1511
            userLog.setTopicUuid(slide.getTopicUuid());
1512
            userLog.setCapsuleUuid(slide.getCapsuleUuid());
1513
            userLog.setSlideUuid(slide.getUuid());
1514
            userLog.setAddedOn(dateOn);
1515
 
1516
            userLogDao.insert(userLog);
1517
            try {
1518
                JSONObject json = userLog.toJson();
1519
                json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1520
 
1521
                sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1522
                syncDao.insert(sync);
1523
            } catch (JSONException e) {
1524
            }
1525
 
1526
 
1527
            if(progressSlide.getCompleted() == 1) {
1528
                userLog = new UserLog();
1529
                userLog.setUserUuid(preference.getUserUuid());
1530
                userLog.setActivity(Constants.USER_LOG_ACTIVITY_APPROVED_TEST);
1531
                userLog.setCompanyUuid(topic.getCompanyUuid());
1532
                userLog.setTopicUuid(slide.getTopicUuid());
1533
                userLog.setCapsuleUuid(slide.getCapsuleUuid());
1534
                userLog.setSlideUuid(slide.getUuid());
1535
                userLog.setAddedOn(dateOn);
1536
 
1537
                userLogDao.insert(userLog);
1538
                try {
1539
                    JSONObject json = userLog.toJson();
1540
                    json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1541
 
1542
                    sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1543
                    syncDao.insert(sync);
1544
                } catch (JSONException e) {
1545
                }
1546
 
1547
            } else {
1548
                if(progressSlide.getCompleted() == 1) {
1549
                    userLog = new UserLog();
1550
                    userLog.setUserUuid(preference.getUserUuid());
1551
                    userLog.setActivity( Constants.USER_LOG_ACTIVITY_VIEW_SLIDE);
1552
                    userLog.setCompanyUuid(topic.getCompanyUuid());
1553
                    userLog.setTopicUuid(slide.getTopicUuid());
1554
                    userLog.setCapsuleUuid(slide.getCapsuleUuid());
1555
                    userLog.setSlideUuid(slide.getUuid());
1556
                    userLog.setAddedOn(dateOn);
1557
 
1558
                    userLogDao.insert(userLog);
1559
                    try {
1560
                        JSONObject json = userLog.toJson();
1561
                        json.put(Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME, Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG);
1562
 
1563
                        sync = new Sync(Constants.SYNC_ADAPTER_TYPE_SYNC, json.toString());
1564
                        syncDao.insert(sync);
1565
                    } catch (JSONException e) {
1566
                    }
1567
                }
1568
            }
1569
        }
1570
 
1571
        requestExecuteSyncAdapter();
1572
    }
1573
 
1574
    @Override
1575
    public void launchVideoViewer(String videoAudioUrl)
1576
    {
1577
 
3 gabriel 1578
        Intent intent = new Intent(getApplicationContext(), VideoAudioActivity.class);
1 gabriel 1579
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1580
        intent.putExtra("deviceId", preference.getDeviceUuid());
1581
        intent.putExtra("password", preference.getPassword());
1582
        //startActivityForResult(intent, Constants.REQUEST_CODE_VIDEO);
1583
 
1584
        mLauncher.launch(intent);
1585
 
1586
    }
1587
 
1588
    @Override
1589
    public void launchAudioViewer(String videoAudioUrl)
1590
    {
1591
 
3 gabriel 1592
        Intent intent = new Intent(getApplicationContext(), VideoAudioActivity.class);
1 gabriel 1593
        intent.putExtra("videoAudioUrl",videoAudioUrl);
1594
        intent.putExtra("deviceId", preference.getDeviceUuid());
1595
        intent.putExtra("password", preference.getPassword());
1596
        //startActivityForResult(intent, Constants.REQUEST_CODE_AUDIO);
1597
 
1598
 
1599
        mLauncher.launch(intent);
1600
    }
1601
 
1602
    @Override
1603
    public void launchTextViewer(String description)
1604
    {
3 gabriel 1605
        Intent intent = new Intent(getApplicationContext(),TextActivity.class);
1 gabriel 1606
        intent.putExtra("description",description);
1607
 
1608
        //startActivityForResult(intent, Constants.REQUEST_CODE_TEXT);
1609
 
1610
        mLauncher.launch(intent);
1611
    }
1612
 
1613
 
1614
    @Override
1615
    public void launchDocumentViewer(String file)
1616
    {
1617
 
3 gabriel 1618
        Intent intent = new Intent(getApplicationContext(),PdfActivity.class);
1 gabriel 1619
        intent.putExtra("documentUrl",file);
1620
        intent.putExtra("deviceId", preference.getDeviceUuid());
1621
        intent.putExtra("password", preference.getPassword());
1622
 
1623
        //startActivityForResult(intent, Constants.REQUEST_CODE_PDF);
1624
 
1625
        mLauncher.launch(intent);
1626
    }
1627
 
1628
    @Override
1629
    public void launchQuizViewer(String quizUuid)
1630
    {
1631
        ProgressDao progressDao = mAppDatabase.getProgressDao();
19 gabriel 1632
        Progress progress = progressDao.selectBySlideUuidAndUserUuid(preference.getSlideUuidActive(), preference.getUserUuid());
1 gabriel 1633
 
1634
        boolean launch = false;
1635
        if(progress != null && progress.getCompleted() == 0) {
1636
 
1637
            Calendar calendar = Calendar.getInstance();
1638
            Date date = calendar.getTime();
1639
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
1640
            try {
1641
                Long updateOn = simpleDateFormat.parse(progress.getUpdatedOn()).getTime();
1642
 
1643
                //30 minutes
1644
                long mintime = 30 * 60 * 1000;
1645
                if(date.getTime() - updateOn >  mintime ) {
1646
                    launch = true;
1647
                }
1648
 
1649
                launch = true;
1650
 
1651
            } catch(Exception e) {
1652
 
1653
            }
1654
 
1655
 
1656
        } else {
1657
            launch = true;
1658
        }
1659
 
1660
        if(launch) {
1661
 
1662
            QuizDao quizDao = mAppDatabase.getQuizDao();
1663
            Quiz quiz = quizDao.selectByUuid(quizUuid);
1664
 
1665
            TopicDao topicDao = mAppDatabase.getTopicDao();
1666
            Topic topic = topicDao.selectByUuid(preference.getTopicUuidActive());
1667
 
1668
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1669
            Capsule capsule = capsuleDao.selectByUuid(preference.getCapsuleUuidActive());
1670
 
1671
            SlideDao slideDao = mAppDatabase.getSlideDao();
1672
            Slide slide = slideDao.selectByUuid(preference.getSlideUuidActive());
1673
 
1674
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1675
            List<Question> questions = questionDao.selectAllByQuizUuid(quiz.getUuid());
1676
 
1677
 
1678
            List<Answer> answers;
1679
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1680
 
3 gabriel 1681
            Intent intent = new Intent(getApplicationContext(), QuizActivity.class);
1 gabriel 1682
           // intent.putExtra("companyUuid", topic.getCompanyUuid());
1683
           // intent.putExtra("topicUuid", topic.getUuid());
1684
            //intent.putExtra("capsuleUuid", capsule.getUuid());
1685
            //intent.putExtra("slideUuid", slide.getUuid());
1686
            //intent.putExtra("userUuid", preference.getUserUuid());
1687
            //intent.putExtra("quizUuid", quizUuid);
1688
 
1689
 
1690
            intent.putExtra("quiz_uuid", quiz.getUuid());
1691
            intent.putExtra("quiz_company_uuid", quiz.getCompanyUuid());
1692
            intent.putExtra("quiz_name", quiz.getName());
1693
            intent.putExtra("quiz_points", quiz.getPoints());
1694
            intent.putExtra("quiz_max_time", quiz.getMaxTime());
1695
            intent.putExtra("quiz_minimum_points_required", quiz.getMinimumPointsRequired());
1696
            intent.putExtra("quiz_failed", quiz.getFailed());
1697
            intent.putExtra("quiz_text", quiz.getText());
1698
 
1699
            intent.putExtra("questions", questions.size());
1700
            int i = 1;
1701
            int j = 1;
1702
            for(Question question : questions) {
1703
                intent.putExtra("question" + i + "_uuid", question.getUuid());
1704
                intent.putExtra("question" + i + "_text", question.getText());
1705
                intent.putExtra("question" + i + "_max_length", question.getMaxlength());
1706
                intent.putExtra("question" + i + "_position", question.getPosition());
1707
                intent.putExtra("question" + i + "_points", question.getPoints());
1708
                intent.putExtra("question" + i + "_type", question.getType());
1709
 
1710
                answers = answerDao.selectAllByQuestionUuid(question.getUuid());
1711
                intent.putExtra("question" + i + "_answers", answers.size());
1712
 
1713
                j = 1;
1714
                for(Answer answer : answers) {
1715
                    intent.putExtra("question" + i + "_answer_uuid" + j, answer.getUuid());
1716
                    intent.putExtra("question" + i + "_answer_text" + j, answer.getText());
1717
                    intent.putExtra("question" + i + "_answer_points" + j, answer.getPoints());
1718
                    intent.putExtra("question" + i + "_answer_correct" + j, answer.getCorrect());
1719
                    j++;
1720
                }
1721
 
1722
                i++;
1723
            }
1724
 
1725
 
1726
 
1727
            //startActivityForResult(intent, Constants.REQUEST_CODE_QUIZ);
1728
 
1729
            mLauncher.launch(intent);
1730
        } else {
1731
            showMessageSnackBar(getString(R.string.error_retry_quiz_min_time));
1732
        }
1733
    }
1734
 
1735
 
1736
    @Override
1737
    public Preference getPreference() {
1738
        return preference;
1739
    }
1740
 
1741
    @Override
1742
    public void reloadNavHeader() {
1743
        Log.d(TAG, "User Image = " + preference.getImage());
8 gabriel 1744
//        navHeaderUserName.setText((preference.getFirstName() + " " + preference.getLastName()).trim());
1745
  //      navHeaderUserEmail.setText(preference.getEmail());
1 gabriel 1746
 
1747
 
1748
 
1749
        Log.d(TAG, preference.getImage());
1750
        if(!TextUtils.isEmpty(preference.getImage())) {
1751
 
1752
            TimeZone timeZone = TimeZone.getTimeZone("UTC");
1753
            Calendar calendar = Calendar.getInstance(timeZone);
1754
            TimeZone tz = calendar.getTimeZone();
1755
            int created =  (int) (calendar.getTimeInMillis() / 1000);
1756
 
1757
            Random random = new Random(created);
1758
            int rand = 1000 + random.nextInt(8999);
1759
 
1760
 
1761
 
1762
 
1763
            Log.d(TAG, "token = " + preference.getDeviceUuid());
1764
            Log.d(TAG, "created = " + created);
1765
            Log.d(TAG, "rand = " + rand);
1766
            Log.d(TAG, "calc = " + preference.getPassword() + ':' +  created + ':' + rand);
1767
 
1768
            String secret = MD5.generar(preference.getPassword() + ':' +  created + ':' + rand);
1769
 
1770
            GlideUrl url = new GlideUrl(preference.getImage(), new LazyHeaders.Builder()
1771
                    .addHeader(Constants.HTTP_HEADER_ACCEPT, Constants.HTTP_HEADER_ACCEPT_VALUE)
1772
                    .addHeader(Constants.HTTP_HEADER_SECURITY_TOKEN, preference.getDeviceUuid())
1773
                    .addHeader(Constants.HTTP_HEADER_SECURITY_SECRET, secret)
1774
                    .addHeader(Constants.HTTP_HEADER_SECURITY_CREATED, String.valueOf(created))
1775
                    .addHeader(Constants.HTTP_HEADER_SECURITY_RAND, String.valueOf(rand))
1776
                    .build());
1777
 
1778
            RequestOptions options = new RequestOptions()
1779
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
1780
 
3 gabriel 1781
            Glide.with(getApplicationContext()).load(url)
1 gabriel 1782
                    .thumbnail()
1783
                    .apply(options)
1784
                    .into(navHeaderUserImage);
1785
        }
1786
    }
1787
 
1788
    public void requestCheckChanges()
1789
    {
1790
        Log.d(TAG, "requestCheckChanges");
1791
        try {
1792
 
1793
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1794
            List<Capsule> capsules = capsuleDao.selectAll();
1795
 
1796
            if(capsules.size() > 0) {
1797
                //ArrayList<String> ids = new ArrayList<>();
1798
 
1799
                TimeZone timeZone = TimeZone.getTimeZone("UTC");
1800
                Calendar calendar = Calendar.getInstance(timeZone);
1801
                TimeZone tz = calendar.getTimeZone();
1802
                int created =  (int) (calendar.getTimeInMillis() / 1000);
1803
 
1804
                Random random = new Random(created);
1805
                int rand = 1000 + random.nextInt(8999);
1806
 
1807
 
1808
                //Log.d("requestCheckChanges", "token = " + preference.getDeviceUuid());
1809
                //Log.d("requestCheckChanges", "created = " + created);
1810
               // Log.d("requestCheckChanges", "rand = " + rand);
1811
                //Log.d("requestCheckChanges", "calc = " + preference.password + ':' +  created + ':' + rand);
1812
 
1813
                String secret = MD5.generar(preference.getPassword() + ':' +  created + ':' + rand);
1814
 
1815
                //Log.d("requestCheckChanges", "secret = " + secret);
1816
 
1817
 
1818
                FormBody.Builder formBodyCheckChangeBuilder = new FormBody.Builder();
1819
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_DEVICE_UUID, preference.getDeviceUuid());
1820
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_DATE_CHANGES, preference.getMaxDateChanges());
1821
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_IS_FOREGROUND, String.valueOf(isForeground ? 1 : 0));
1822
                Http http = new Http(this.getCacheDir(), preference.getDeviceUuid(), secret, created, rand);
1823
                OkHttpClient client = http.getHttpClient(false);
1824
 
1825
 
1826
 
1827
                formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(capsules.size()));
1828
                //formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_MAX_IDS, String.valueOf(0));
1829
 
1830
              int i = 1;
1831
                for(Capsule capsule : capsules)
1832
                {
1833
                    Log.d("requestCheckChanges", "id" + i + " = " + capsule.getTopicUuid() + "|" + capsule.getUuid());
1834
 
1835
 
1836
                    formBodyCheckChangeBuilder.add(Constants.POST_MICROLEARNING_CHECK_CHANGES_ID + i, capsule.getTopicUuid() + "|" + capsule.getUuid());
1837
                    i++;
1838
                }
1839
 
1840
 
1841
 
1842
                RequestBody formBody = formBodyCheckChangeBuilder.build();
1843
 
1844
                Log.d(TAG, "URL = " + Configuration.URL_CHECK_CHANGES);
1845
                Request request = new Request.Builder()
1846
                        .url(Configuration.URL_CHECK_CHANGES)
1847
                        .post(formBody)
1848
                        .build();
1849
 
1850
                Call call = client.newCall(request);
1851
                call.enqueue(new okhttp3.Callback() {
1852
                    public void onResponse(Call call, Response response)
1853
                            throws IOException {
1854
 
1855
 
1856
 
1857
                        processResponseServerChanges(response.body().string());
1858
                    }
1859
 
1860
                    public void onFailure(Call call, IOException e) {
1861
                        Log.d(TAG, "Error :  " +  e.getMessage());
1862
                    }
1863
                });
1864
            }
1865
 
1866
 
1867
 
1868
        } catch(Exception e) {
1869
 
1870
        }
1871
    }
1872
 
1873
 
1874
    public void syncFromServer(JSONObject data)
1875
    {
1876
        try {
1877
            JSONObject objUser = data.getJSONObject("user");
1878
            String userUuid = objUser.getString("uuid");
1879
 
1880
 
1881
            AnswerDao answerDao = mAppDatabase.getAnswerDao();
1882
            QuestionDao questionDao = mAppDatabase.getQuestionDao();
1883
            QuizDao quizDao = mAppDatabase.getQuizDao();
1884
            SlideDao slideDao = mAppDatabase.getSlideDao();
1885
            CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
1886
            TopicDao topicDao = mAppDatabase.getTopicDao();
1887
            CompanyDao companyDao = mAppDatabase.getCompanyDao();
1888
            UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
1889
 
1890
 
1891
 
1892
            ProgressDao progressDao = mAppDatabase.getProgressDao();
1893
            progressDao.removeAllUserUuidNotEqual(userUuid);
1894
 
1895
 
1896
            UserLogDao userLogDao = mAppDatabase.getUserLogDao();
1897
            userLogDao.removeAllUserUuidNotEqual(userUuid);
1898
 
1899
            JSONArray arrayCapsules;
1900
            JSONArray arraySlides;
1901
            JSONArray arrayAnswers;
1902
            JSONArray arrayQuestions;
1903
            JSONArray arrayProgress;
1904
            JSONArray arrayQuizzes;
1905
            JSONArray arrayUserLog;
1906
 
1907
            JSONObject objTopic;
1908
            JSONObject objCapsule;
1909
            JSONObject objSlide;
1910
            JSONObject objAnswer;
1911
            JSONObject objQuestion;
1912
            JSONObject objQuiz;
1913
            JSONObject objProgress;
1914
            JSONObject objUserLog;
1915
            int i,j,x;
1916
 
1917
            if(data.has("progress")) {
1918
 
1919
                arrayProgress = data.getJSONArray("progress");
1920
                for (i = 0; i < arrayProgress.length(); i++) {
1921
                    objProgress = arrayProgress.getJSONObject(i);
1922
 
1923
 
1924
                    Progress progress = null;
1925
 
1926
 
1927
                    userUuid = objProgress.getString("user_uuid");
1928
                    String type = objProgress.getString("type");
1929
                    String topicUuid = objProgress.getString("topic_uuid");
1930
                    String capsuleUuid = objProgress.getString("capsule_uuid");
1931
                    String slideUuid = objProgress.getString("slide_uuid");
1932
 
1933
                    if(type == Constants.PROGERSS_TYPE_SLIDE) {
1934
                        progress = progressDao.selectBySlideUuidAndUserUuid(slideUuid, userUuid);
1935
                    } else if(type == Constants.PROGERSS_TYPE_CAPSULE) {
1936
                        progress = progressDao.selectByCapsuleUuidAndUserUuid(capsuleUuid, userUuid);
1937
                    } else if(type == Constants.PROGERSS_TYPE_TOPIC) {
1938
                        progress = progressDao.selectByTopicUuidAndUserUuid(topicUuid, userUuid);
1939
                    }
1940
 
1941
 
1942
                    if(progress == null) {
1943
                        progress = new Progress();
1944
                        progress.setUserUuid(userUuid);
1945
                        progress.setCompanyUuid(objProgress.getString("company_uuid"));
1946
                        progress.setTopicUuid(topicUuid);
1947
                        progress.setCapsuleUuid(capsuleUuid);
1948
                        progress.setSlideUuid(slideUuid);
1949
                        progress.setProgress(objProgress.getDouble("progress"));
1950
                        progress.setTotalSlides(objProgress.getInt("total_slides"));
1951
                        progress.setViewSlides(objProgress.getInt("view_slides"));
1952
                        progress.setType(type);
1953
                        progress.setReturning(objProgress.getInt("returning"));
1954
                        progress.setReturningAfterCompleted(objProgress.getInt("returning_after_completed"));
1955
                        progress.setCompleted(objProgress.getInt("completed"));
1956
                        progress.setAddedOn(objProgress.getString("added_on"));
1957
                        progress.setUpdatedOn(objProgress.getString("updated_on"));
1958
 
1959
                        progressDao.insert(progress);
1960
                    }
1961
 
1962
 
1963
                }
1964
            }
1965
 
1966
            if(data.has("userlog")) {
1967
                arrayUserLog = data.getJSONArray("userlog");
1968
                for (i = 0; i < arrayUserLog.length(); i++) {
1969
                    objUserLog = arrayUserLog.getJSONObject(i);
1970
 
1971
                    userUuid = objUserLog.getString("user_uuid");
1972
                    String activity = objUserLog.getString("activity");
1973
                    String added_on = objUserLog.getString("added_on");
1974
 
1975
                    UserLog userLog = userLogDao.selectOneByUserUuidAndActivityAndAddedOn(userUuid, activity, added_on);
1976
                    if(userLog == null) {
1977
                        userLog = new UserLog();
1978
                        userLog.setUserUuid(objUserLog.getString("user_uuid"));
1979
                        userLog.setCompanyUuid(objUserLog.getString("company_uuid"));
1980
                        userLog.setTopicUuid(objUserLog.getString("topic_uuid"));
1981
                        userLog.setCapsuleUuid(objUserLog.getString("capsule_uuid"));
1982
                        userLog.setSlideUuid(objUserLog.getString("slide_uuid"));
1983
                        userLog.setActivity(objUserLog.getString("activity"));
1984
                        userLog.setAddedOn(objUserLog.getString("added_on"));
1985
                        userLogDao.insert(userLog);
1986
                    }
1987
                }
1988
            }
1989
 
19 gabriel 1990
            String uuid;
1991
            Company company;
1 gabriel 1992
            if(data.has("quizzes")) {
19 gabriel 1993
                Quiz quiz;
1994
                Question question;
1995
                Answer answer;
1996
 
1 gabriel 1997
                arrayQuizzes = data.getJSONArray("quizzes");
1998
                for (i = 0; i < arrayQuizzes.length(); i++) {
1999
                    objQuiz = arrayQuizzes.getJSONObject(i);
19 gabriel 2000
                    uuid = objQuiz.getString("company_uuid");
2001
                    company = companyDao.selectByUuid(uuid);
1 gabriel 2002
                    if (company == null) {
2003
                        company = new Company();
2004
                        company.setUuid(objQuiz.getString("company_uuid"));
2005
                        company.setName(objQuiz.getString("company_name"));
2006
                        company.setImage(objQuiz.getString("company_image"));
2007
 
2008
                        companyDao.insert(company);
19 gabriel 2009
                    } else {
2010
                        company.setName(objQuiz.getString("company_name"));
2011
                        company.setImage(objQuiz.getString("company_image"));
2012
 
2013
                        companyDao.update(company);
1 gabriel 2014
                    }
2015
 
19 gabriel 2016
                    uuid =  objQuiz.getString("uuid");
2017
                    quiz = quizDao.selectByUuid(uuid);
1 gabriel 2018
 
19 gabriel 2019
                    if(quiz == null) {
2020
                        quiz = new Quiz();
2021
                        quiz.setUuid(  objQuiz.getString("uuid"));
2022
                        quiz.setCompanyUuid(  company.getUuid() );
2023
                        quiz.setFailed(  objQuiz.getString("failed"));
2024
                        quiz.setName(  objQuiz.getString("name"));
2025
                        quiz.setText(  objQuiz.getString("text"));
2026
                        quiz.setPoints(  objQuiz.getInt("points"));
2027
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2028
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2029
                        quizDao.insert(quiz);
2030
 
2031
                    } else {
2032
                        quiz.setCompanyUuid(  company.getUuid() );
2033
                        quiz.setFailed(  objQuiz.getString("failed"));
2034
                        quiz.setName(  objQuiz.getString("name"));
2035
                        quiz.setText(  objQuiz.getString("text"));
2036
                        quiz.setPoints(  objQuiz.getInt("points"));
2037
                        quiz.setMinimumPointsRequired(objQuiz.getInt("minimum_points_required"));
2038
                        quiz.setMaxTime( objQuiz.getInt("max_time"));
2039
                        quizDao.update(quiz);
2040
                    }
2041
 
1 gabriel 2042
                    arrayQuestions = objQuiz.getJSONArray("questions");
2043
                    for (j = 0; j < arrayQuestions.length(); j++) {
2044
                        objQuestion = arrayQuestions.getJSONObject(j);
2045
 
19 gabriel 2046
                        uuid = objQuestion.getString("uuid");
2047
                        question = questionDao.selectByUuid(uuid);
2048
                        if(question == null) {
2049
                            question = new Question();
2050
                            question.setQuizUuid( quiz.getUuid());
2051
                            question.setUuid(uuid) ;
2052
                            question.setText( objQuestion.getString("text"));
2053
                            question.setType( objQuestion.getString("type"));
2054
                            question.setPoints( objQuestion.getInt("points"));
2055
                            question.setMaxlength( objQuestion.getInt("maxlength"));
1 gabriel 2056
 
19 gabriel 2057
                            questionDao.insert(question);
2058
                        } else {
2059
                            question.setQuizUuid( quiz.getUuid());
2060
                            question.setText( objQuestion.getString("text"));
2061
                            question.setType( objQuestion.getString("type"));
2062
                            question.setPoints( objQuestion.getInt("points"));
2063
                            question.setMaxlength( objQuestion.getInt("maxlength"));
2064
 
2065
                            questionDao.update(question);
2066
                        }
2067
 
2068
 
2069
 
2070
 
1 gabriel 2071
                        arrayAnswers = objQuestion.getJSONArray("answers");
2072
                        for (x = 0; x < arrayAnswers.length(); x++) {
2073
                            objAnswer = arrayAnswers.getJSONObject(x);
2074
 
19 gabriel 2075
                            uuid = objAnswer.getString("uuid");
2076
                            answer = answerDao.selectByUuid(uuid);
1 gabriel 2077
 
19 gabriel 2078
                            if(answer == null) {
1 gabriel 2079
 
19 gabriel 2080
                                answer = new Answer();
2081
                                answer.setQuestionUuid(question.getUuid());
2082
                                answer.setUuid(uuid);
2083
                                answer.setText(objAnswer.getString("text"));
2084
                                answer.setPoints(objAnswer.getInt("points"));
2085
                                answer.setCorrect(objAnswer.getString("correct"));
2086
 
2087
                                answerDao.insert(answer);
2088
                            } else {
2089
                                answer.setQuestionUuid(question.getUuid());
2090
                                answer.setText(objAnswer.getString("text"));
2091
                                answer.setPoints(objAnswer.getInt("points"));
2092
                                answer.setCorrect(objAnswer.getString("correct"));
2093
                                answerDao.update(answer);
2094
                            }
2095
                        }
1 gabriel 2096
                    }
2097
                }
2098
            }
2099
 
2100
 
2101
 
2102
 
2103
 
2104
            if(data.has("topics")) {
19 gabriel 2105
                Topic topic;
2106
                Capsule capsule;
2107
                Slide slide;
1 gabriel 2108
 
2109
                JSONArray arrayTopics = data.getJSONArray("topics");
2110
                for (i = 0; i < arrayTopics.length(); i++) {
2111
                    objTopic = arrayTopics.getJSONObject(i);
2112
 
19 gabriel 2113
                    uuid = objTopic.getString("company_uuid");
2114
                    company = companyDao.selectByUuid(uuid);
1 gabriel 2115
                    if (company == null) {
2116
                        company = new Company();
2117
                        company.setUuid(objTopic.getString("company_uuid"));
2118
                        company.setName(objTopic.getString("company_name"));
2119
                        company.setImage(objTopic.getString("company_image"));
2120
 
2121
                        companyDao.insert(company);
19 gabriel 2122
                    } else {
2123
                        company.setName(objTopic.getString("company_name"));
2124
                        company.setImage(objTopic.getString("company_image"));
2125
 
2126
                        companyDao.update(company);
1 gabriel 2127
                    }
2128
 
19 gabriel 2129
                    uuid = objTopic.getString("uuid");
2130
                    topic = topicDao.selectByUuid(uuid);
1 gabriel 2131
 
19 gabriel 2132
                    if (topic == null) {
2133
                        topic = new Topic();
2134
                        topic.setUuid(uuid);
2135
                        topic.setCompanyUuid(company.getUuid());
2136
                        topic.setName(objTopic.getString("name"));
2137
                        topic.setDescription(objTopic.getString("description"));
2138
                        topic.setImage(objTopic.getString("image"));
2139
                        topic.setPosition(objTopic.getInt("position"));
2140
                        topicDao.insert(topic);
2141
                    } else {
2142
                        topic.setCompanyUuid(company.getUuid());
2143
                        topic.setName(objTopic.getString("name"));
2144
                        topic.setDescription(objTopic.getString("description"));
2145
                        topic.setImage(objTopic.getString("image"));
2146
                        topic.setPosition(objTopic.getInt("position"));
2147
                        topicDao.update(topic);
2148
                    }
2149
 
2150
 
2151
 
2152
 
2153
 
1 gabriel 2154
                    arrayCapsules = objTopic.getJSONArray("capsules");
2155
                    for (j = 0; j < arrayCapsules.length(); j++) {
2156
                        objCapsule = arrayCapsules.getJSONObject(j);
19 gabriel 2157
                        uuid = objCapsule.getString("uuid");
2158
                        capsule = capsuleDao.selectByUuid(uuid);
2159
                        if(capsule == null) {
2160
                            capsule = new Capsule();
2161
                            capsule.setTopicUuid(topic.getUuid());
2162
                            capsule.setUuid(uuid);
2163
                            capsule.setName(objCapsule.getString("name"));
2164
                            capsule.setDescription(objCapsule.getString("description"));
2165
                            capsule.setImage(objCapsule.getString("image"));
2166
                            capsule.setPosition(objCapsule.getInt("position"));
2167
                            capsuleDao.insert(capsule);
2168
                        } else {
2169
                            capsule = new Capsule();
2170
                            capsule.setTopicUuid(topic.getUuid());
2171
                            capsule.setName(objCapsule.getString("name"));
2172
                            capsule.setDescription(objCapsule.getString("description"));
2173
                            capsule.setImage(objCapsule.getString("image"));
2174
                            capsule.setPosition(objCapsule.getInt("position"));
2175
                            capsuleDao.update(capsule);
2176
                        }
1 gabriel 2177
 
19 gabriel 2178
 
2179
 
2180
 
1 gabriel 2181
                        arraySlides = objCapsule.getJSONArray("slides");
2182
                        for (x = 0; x < arraySlides.length(); x++) {
2183
                            objSlide = arraySlides.getJSONObject(x);
2184
 
19 gabriel 2185
 
2186
                            uuid = objSlide.getString("uuid");
2187
                            slide = slideDao.selectByUuid(uuid);
2188
 
2189
                            if(slide == null) {
2190
 
2191
                                slide = new Slide();
2192
                                slide.setUuid(uuid);
2193
                                slide.setTopicUuid(capsule.getTopicUuid());
2194
                                slide.setCapsuleUuid(capsule.getUuid());
2195
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2196
                                slide.setName(objSlide.getString("name"));
2197
                                slide.setDescription(objSlide.getString("description"));
2198
                                slide.setPosition(objSlide.getInt("position"));
2199
                                slide.setType(objSlide.getString("type"));
2200
                                slide.setFile(objSlide.getString("file"));
2201
                                slide.setBackground(objSlide.getString("background"));
2202
 
2203
                                slideDao.insert(slide);
2204
                            } else {
2205
                                slide.setTopicUuid(capsule.getTopicUuid());
2206
                                slide.setCapsuleUuid(capsule.getUuid());
2207
                                slide.setQuizUuid(objSlide.getString("quiz_uuid"));
2208
                                slide.setName(objSlide.getString("name"));
2209
                                slide.setDescription(objSlide.getString("description"));
2210
                                slide.setPosition(objSlide.getInt("position"));
2211
                                slide.setType(objSlide.getString("type"));
2212
                                slide.setFile(objSlide.getString("file"));
2213
                                slide.setBackground(objSlide.getString("background"));
2214
 
2215
                                slideDao.update(slide);
2216
                            }
1 gabriel 2217
                        }
2218
 
2219
                    }
2220
 
2221
 
2222
                }
2223
            }
2224
 
19 gabriel 2225
            if(data.has( "extended")) {
1 gabriel 2226
 
19 gabriel 2227
                JSONObject objExtended;
2228
                JSONObject objItem;
2229
                JSONArray objItems;
2230
 
2231
 
2232
 
2233
                UserExtended userExtended;
2234
 
2235
                JSONArray extendedCompanies = data.getJSONArray("extended");
2236
                for(i = 0 ; i < extendedCompanies.length(); i++)
2237
                {
2238
                    objExtended = extendedCompanies.getJSONObject(i);
2239
                    if(objExtended.has("details")) {
2240
                        uuid = objExtended.getString("company_uuid");
2241
 
2242
 
2243
                        company = companyDao.selectByUuid(uuid);
2244
                        if (company == null) {
2245
                            company = new Company();
2246
                            company.setUuid(objExtended.getString("company_uuid"));
2247
                            company.setName(objExtended.getString("company_name"));
2248
                            company.setImage(objExtended.getString("company_image"));
2249
 
2250
                            companyDao.insert(company);
2251
                        } else {
2252
                            company.setName(objExtended.getString("company_name"));
2253
                            company.setImage(objExtended.getString("company_image"));
2254
 
2255
                            companyDao.update(company);
2256
                        }
2257
 
2258
                        objItems = objExtended.getJSONArray("details");
2259
                        for(j = 0 ; j < objItems.length(); j++) {
2260
                            objItem = objItems.getJSONObject(j);
2261
 
2262
                            uuid =  objItem.getString("uuid");
2263
 
2264
                            userExtended = userExtendedDao.selectByUuid(uuid);
2265
                            if(userExtended == null) {
2266
                                userExtended = new UserExtended();
2267
                                userExtended.setCompanyUuid(company.getUuid());
2268
                                userExtended.setUuid(uuid);
2269
                                userExtended.setLabel(objItem.getString("label"));
2270
                                userExtended.setValue(objItem.getString("value"));
2271
                                userExtendedDao.insert(userExtended);
2272
                            } else {
2273
                                userExtended.setCompanyUuid(company.getUuid());
2274
                                userExtended.setLabel(objItem.getString("label"));
2275
                                userExtended.setValue(objItem.getString("value"));
2276
                                userExtendedDao.update(userExtended);
2277
                            }
2278
 
2279
 
2280
 
2281
 
2282
                        }
2283
                    }
2284
                }
2285
 
2286
            }
2287
 
2288
 
1 gabriel 2289
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2290
            if(data.has("max_date_changes")) {
2291
                String max_date_changes = data.getString("max_date_changes");
2292
                Log.d("syncFromServer", "max_date_changes : " + max_date_changes);
2293
 
2294
                if(!TextUtils.isEmpty(max_date_changes)) {
2295
                    preference.setMaxDateChanges(max_date_changes);
2296
                }
2297
            } else {
2298
                Log.d("syncFromServer", "No max_date_changes");
2299
            }
2300
 
2301
            Calendar calendar = Calendar.getInstance();
2302
            Date date = calendar.getTime();
2303
 
2304
            String  addedOn = simpleDateFormat.format(date);
2305
 
2306
            List<Company> companies = mAppDatabase.getCompanyDao().selectAll();
2307
            int companySize = companies.size();
2308
 
2309
            if(companySize > 0) {
2310
 
2311
                if(TextUtils.isEmpty(preference.getCompanyUuidActive())) {
2312
 
2313
                    preference.setCompanyUuidActive(companies.get(0).getUuid());
2314
 
2315
                } else {
2316
 
2317
                    boolean companyExist = false;
19 gabriel 2318
                    for(i = 0; i < companies.size(); i++) {
2319
 
2320
                        if (companies.get(i).getUuid().equals(preference.getCompanyUuidActive())) {
1 gabriel 2321
                            companyExist = true;
19 gabriel 2322
                            break;
1 gabriel 2323
                        }
2324
                    }
2325
 
19 gabriel 2326
                    if(!companyExist && companies.size() > 0) {
1 gabriel 2327
                        preference.setCompanyUuidActive(companies.get(0).getUuid());
2328
                    }
2329
                }
2330
 
2331
            } else {
2332
                preference.setCompanyUuidActive("");
2333
            }
2334
 
2335
 
2336
 
2337
            preference.setLastDataRefresh(addedOn);
2338
            preference.setCompanyCount(companySize);
3 gabriel 2339
            preference.save();
1 gabriel 2340
 
2341
        } catch (JSONException e) {
2342
            Log.d(TAG, e.getMessage());
2343
        }
2344
    }
2345
 
2346
    @Override
2347
    public void requestExecuteSyncAdapter() {
2348
            // Pass the settings flags by inserting them in a bundle
2349
            Bundle settingsBundle = new Bundle();
2350
            settingsBundle.putBoolean(
2351
                    ContentResolver.SYNC_EXTRAS_MANUAL, true);
2352
            settingsBundle.putBoolean(
2353
                    ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
2354
 
2355
            ContentResolver.requestSync(mAccount, Constants.AUTHORITY, settingsBundle);
2356
    }
2357
 
2358
 
2359
    private void processResponseServerChanges(String dataString)
2360
    {
2361
 
2362
        Log.d(TAG, "processResponseServerChanges = " + dataString);
2363
 
2364
        try {
2365
            JSONObject objJSON = new JSONObject(dataString);
2366
            boolean success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2367
 
2368
 
2369
            if(success) {
2370
                Calendar calendar = Calendar.getInstance();
2371
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2372
                preference.setLastDataRefresh(simpleDateFormat.format(calendar.getTime()));
3 gabriel 2373
                preference.save();
1 gabriel 2374
 
2375
                String max_date_changes = "";
2376
                boolean processChanges = false;
2377
 
2378
                JSONObject data = objJSON.getJSONObject("data");
11 gabriel 2379
 
2380
 
1 gabriel 2381
                if(data.has("max_date_changes") && data.has("new_capsules")) {
2382
                    int new_capsules = data.getInt("new_capsules");
2383
                    max_date_changes = data.getString("max_date_changes");
2384
 
2385
 
2386
 
2387
 
2388
                    processChanges = new_capsules > 0 && !max_date_changes.equals(preference.getMaxDateChanges());
2389
                } else {
2390
                    processChanges = false;
2391
                }
2392
 
2393
                if(processChanges && !max_date_changes.isEmpty()) {
2394
                    int new_capsules = data.getInt("new_capsules");
2395
                    String message = new_capsules == 1
2396
                            ? "Hay 1 cápsula nueva disponible"
2397
                            : "Hay " + new_capsules + " cápsulas disponible";
2398
 
2399
 
11 gabriel 2400
                    showMessageSnackBarWithClose(message);
1 gabriel 2401
 
2402
 
11 gabriel 2403
 
1 gabriel 2404
                    preference.setMaxDateChanges(max_date_changes);
2405
 
2406
                    if(!isForeground) {
2407
                        String body = new_capsules == 1
2408
                                ? "Hay 1 cápsula nueva disponible"
2409
                                : "Hay " + new_capsules + " cápsulas disponible";
11 gabriel 2410
                        showFcmNotification("Nuevo contenido", body, new_capsules);
1 gabriel 2411
                    }
2412
 
2413
                    /*
2414
                    if(!isForeground) {
2415
                        String body = new_capsules == 1
2416
                                ? "Hay 1 cápsula nueva disponible"
2417
                                : "Hay " + new_capsules + " cápsulas disponible";
2418
                        showFcmNotification("Nuevo contenido", body, new_capsules);
2419
 
2420
 
2421
                        AnswerDao answerDao = mAppDatabase.getAnswerDao();
2422
                        answerDao.removeAll();
2423
 
2424
                        QuestionDao questionDao = mAppDatabase.getQuestionDao();
2425
                        questionDao.removeAll();
2426
 
2427
                        QuizDao quizDao = mAppDatabase.getQuizDao();
2428
                        quizDao.removeAll();
2429
 
2430
                        SlideDao slideDao = mAppDatabase.getSlideDao();
2431
                        slideDao.removeAll();
2432
 
2433
                        CapsuleDao capsuleDao = mAppDatabase.getCapsuleDao();
2434
                        capsuleDao.removeAll();
2435
 
2436
                        TopicDao topicDao = mAppDatabase.getTopicDao();
2437
                        topicDao.removeAll();
2438
 
2439
                        CompanyDao companyDao = mAppDatabase.getCompanyDao();
2440
                        companyDao.removeAll();
2441
 
2442
                        UserExtendedDao userExtendedDao = mAppDatabase.getUserExtendedDao();
2443
                        userExtendedDao.removeAll();
2444
 
2445
 
2446
                        this.syncFromServer(data);
2447
 
2448
 
2449
                        if(!TextUtils.isEmpty(preference.getSlideUuidActive())) {
2450
 
2451
                            Slide slide = mAppDatabase.getSlideDao().selectByUuid(preference.getSlideUuidActive());
2452
                            if(slide == null) {
2453
                                preference.setFragmentIdxActive(Constants.IDX_FRAGMENT_TOPICS);
2454
                                preference.save(this);
2455
                            }
2456
 
2457
                        }
2458
                    }*/
2459
                }
2460
            }
2461
        } catch (JSONException e) {
2462
            Log.d(TAG, e.getMessage());
2463
        }
2464
    }
2465
 
2466
    @Override
2467
    public AppDatabase getDatabase() {
2468
        return mAppDatabase;
2469
    }
2470
 
2471
    @Override
2472
    public void syncToServerOrCheckChanges()
2473
    {
2474
        if(TextUtils.isEmpty(preference.getDeviceUuid())) {
2475
            return;
2476
        }
2477
 
2478
        SyncDao syncDao = mAppDatabase.getSyncDao();
2479
        List<Sync> records = syncDao.selectBatch();
2480
 
2481
        if(records.size() > 0) {
2482
            syncToServer(records);
2483
        } else {
2484
 
2485
                long timeLast = 0;
2486
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_DATETIME_SERVICE);
2487
                if (!TextUtils.isEmpty(preference.getLastDataRefresh())) {
2488
                    try {
2489
                        timeLast = simpleDateFormat.parse(preference.getLastDataRefresh()).getTime();
2490
                    } catch (Exception e) {
2491
 
2492
                    }
2493
 
2494
                }
2495
 
2496
 
2497
                Calendar calendar = Calendar.getInstance();
2498
                long timeNow = calendar.getTime().getTime();
2499
                 if (timeNow > (timeLast + Constants.CHECK_CHANGES_INTERVAL)) {
2500
                    requestCheckChanges();
2501
                }
2502
        }
2503
    }
2504
 
2505
 
2506
 
2507
    public void syncToServer(List<Sync> records)
2508
    {
2509
 
2510
 
2511
 
2512
        int maxRecordsSyncBatch = 0;
2513
        FormBody.Builder formBodyBatchBuilder = new FormBody.Builder();
2514
        formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_DEVICE_UUID, preference.getDeviceUuid());
2515
 
2516
        for(Sync record : records)
2517
        {
2518
            Log.d(TAG, "SyncRecord ID = " + record.getId() + " Data : "  + record.getData() + " Type= " + record.getType());
2519
 
2520
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {
2521
                Log.d(TAG, "Device");
2522
                isSyncDevice = true;
2523
 
2524
                try {
2525
                    Http http = new Http(this.getCacheDir());
2526
                    OkHttpClient client = http.getHttpClient(false);
2527
 
2528
                    RequestBody formBody = new FormBody.Builder()
2529
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID,  String.valueOf(Configuration.APPLICATION_ID))
2530
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
2531
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
2532
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
2533
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE  + " " + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName())
2534
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
2535
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
2536
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
2537
                            .build();
2538
 
2539
                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
2540
                    Request request = new Request.Builder()
2541
                            .url(Configuration.URL_DEVICE)
2542
                            .post(formBody)
2543
                            .build();
2544
 
2545
                    Call call = client.newCall(request);
2546
                    call.enqueue(new okhttp3.Callback() {
2547
                        public void onResponse(Call call, Response response)
2548
                                throws IOException {
2549
                            isSyncDevice = false;
2550
                            Log.d(TAG, "Response Device :  " +  response.body().toString());
2551
 
2552
                            processResponseSyncToServer(response.body().string());
2553
                        }
2554
 
2555
                        public void onFailure(Call call, IOException e) {
2556
                            isSyncDevice = false;
2557
                            Log.d(TAG, "Error :  " +  e.getMessage());
2558
                        }
2559
                    });
2560
                } catch (Exception e) {
2561
                }
2562
            }
2563
 
2564
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken) {
2565
                isSyncToken = true;
2566
                Log.d(TAG, "FCM");
2567
 
2568
                try {
2569
                    Http http = new Http(this.getCacheDir());
2570
                    OkHttpClient client = http.getHttpClient(false);
2571
 
2572
                    RequestBody formBody = new FormBody.Builder()
2573
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID,preference.getDeviceUuid())
2574
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
2575
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
2576
                            .build();
2577
 
2578
                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
2579
                    Request request = new Request.Builder()
2580
                            .url(Configuration.URL_FCM)
2581
                            .post(formBody)
2582
                            .build();
2583
 
2584
                    Call call = client.newCall(request);
2585
                    call.enqueue(new okhttp3.Callback() {
2586
                        public void onResponse(Call call, Response response)
2587
                                throws IOException {
2588
                            isSyncToken = false;
2589
                            processResponseSyncToServer(response.body().string());
2590
                        }
2591
 
2592
                        public void onFailure(Call call, IOException e) {
2593
                            Log.d(TAG, "Error :  " +  e.getMessage());
2594
                            isSyncToken = false;
2595
                        }
2596
                    });
2597
                } catch (Exception e) {
2598
 
2599
 
2600
                }
2601
            }
2602
 
2603
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_SYNC ) {
2604
                Log.d(TAG, "SYNC BATCH");
2605
                maxRecordsSyncBatch++;
2606
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_DATA + maxRecordsSyncBatch, record.getData());
2607
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_RECORD_SYNC_ID + maxRecordsSyncBatch, String.valueOf(record.getId()));
2608
            }
2609
        }
2610
 
2611
 
2612
        if(maxRecordsSyncBatch > 0 && !isSyncBatch) {
2613
            Log.d(TAG, "Sync Batch");
2614
            isSyncBatch = true;
2615
 
2616
            try {
2617
                Http http = new Http(this.getCacheDir());
2618
                OkHttpClient client = http.getHttpClient(false);
2619
 
2620
                formBodyBatchBuilder.add(Constants.POST_SYNC_BATCH_FIELD_MAX_RECORDS, String.valueOf(maxRecordsSyncBatch));
2621
                RequestBody formBody = formBodyBatchBuilder.build();
2622
 
2623
                Log.d(TAG, "URL = " + Configuration.URL_SYNC_BATCH);
2624
                Request request = new Request.Builder()
2625
                    .url(Configuration.URL_SYNC_BATCH)
2626
                    .post(formBody)
2627
                    .build();
2628
 
2629
                Call call = client.newCall(request);
2630
                call.enqueue(new okhttp3.Callback() {
2631
                    public void onResponse(Call call, Response response) throws IOException {
2632
                        isSyncBatch = false;
2633
                        processResponseServerBatch(response.body().string());
2634
                    }
2635
 
2636
                    public void onFailure(Call call, IOException e) {
2637
                        Log.d(TAG, "Error :  " +  e.getMessage());
2638
                        isSyncBatch = false;
2639
                    }
2640
                });
2641
            } catch (Exception e) {
2642
 
2643
 
2644
            }
2645
        }
2646
 
2647
 
2648
    }
2649
 
2650
    private void processResponseServerBatch(String dataString)
2651
    {
2652
        boolean success = false;
2653
        long sync_id = 0;
2654
 
2655
        Log.d(TAG, "processResponseServer = " + dataString);
2656
        try {
2657
            JSONObject objJSON = new JSONObject(dataString);
2658
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2659
            if(success  && objJSON.has("data")) {
2660
                JSONArray jsonArrayData = objJSON.getJSONArray("data");
2661
 
2662
 
2663
                JSONObject jsonObjectData;
2664
                int max = jsonArrayData.length();
2665
                for(int i = 0; i < max; i++) {
2666
                    jsonObjectData = jsonArrayData.getJSONObject(i);
2667
 
2668
                    if(jsonObjectData.has("success") && jsonObjectData.getBoolean("success")) {
2669
                        sync_id = jsonObjectData.getLong("sync_id");
2670
 
2671
                        mAppDatabase.getSyncDao().remove(sync_id);
2672
 
2673
                    }
2674
 
2675
 
2676
                }
2677
 
2678
 
2679
 
2680
                /*
2681
                if(jsonObjectData.has("message")) {
2682
                    message = jsonObjectData.getString("message");
2683
                }
2684
 
2685
                if(jsonObjectData.has("aes")) {
2686
                    preference.setAes(jsonObjectData.getString("aes"));
2687
                    preference.save(this);
2688
                }
2689
 
2690
                if(jsonObjectData.has("password")) {
2691
                    preference.setPassword(jsonObjectData.getString("password"));
2692
                    preference.save(this);
2693
                }
2694
                */
2695
            }
2696
            Log.d(TAG, "SyncID = " + sync_id);
2697
            if(success && sync_id > 0) {
2698
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2699
                mAppDatabase.getSyncDao().remove(sync_id);
2700
            }
2701
        } catch (JSONException e) {
2702
            e.printStackTrace();
2703
        }
2704
    }
2705
 
2706
    private void processResponseSyncToServer(String dataString)
2707
    {
2708
        boolean success = false;
2709
        long sync_id = 0;
2710
 
2711
        Log.d(TAG, "processResponseServer = " + dataString);
2712
        try {
2713
            JSONObject objJSON = new JSONObject(dataString);
2714
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
2715
            if(success  && objJSON.has("data")) {
2716
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
2717
 
2718
                if(jsonObjectData.has("sync_id")) {
2719
                    sync_id = jsonObjectData.getLong("sync_id");
2720
                }
2721
 
2722
                /*
2723
                if(jsonObjectData.has("message")) {
2724
                    message = jsonObjectData.getString("message");
2725
                }
2726
 
2727
                if(jsonObjectData.has("aes")) {
2728
                    preference.setAes(jsonObjectData.getString("aes"));
2729
                    preference.save(this);
2730
                }
2731
 
2732
                if(jsonObjectData.has("password")) {
2733
                    preference.setPassword(jsonObjectData.getString("password"));
2734
                    preference.save(this);
2735
                }
2736
                */
2737
            }
2738
            Log.d(TAG, "SyncID = " + sync_id);
2739
            if(success && sync_id > 0) {
2740
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
2741
                mAppDatabase.getSyncDao().remove(sync_id);
2742
            }
2743
        } catch (JSONException e) {
2744
            e.printStackTrace();
2745
        }
2746
    }
2747
 
2748
    /*
2749
    private void processResponseServerCheckChanges(String dataString) {
2750
 
2751
        Log.d(TAG, "processResponseServerCheckChanges = " + dataString);
2752
 
2753
        runOnUiThread(new Runnable() {
2754
 
2755
            @Override
2756
            public void run() {
2757
 
2758
                try {
2759
                    JSONObject objJSON = new JSONObject(dataString);
2760
                    boolean success = objJSON.has("success") ? objJSON.getBoolean("success") : false;
2761
                    String message = "";
2762
                    if (objJSON.has("data")) {
2763
                        Object item = objJSON.get("data");
2764
                        if (item instanceof String) {
2765
                            message = item.toString();
2766
                        }
2767
                    }
2768
 
2769
                    if (success) {
2770
                        mAppDatabase.getAnswerDao().removeAll();
2771
                        mAppDatabase.getQuestionDao().removeAll();
2772
                        mAppDatabase.getQuizDao().removeAll();
2773
                        mAppDatabase.getSlideDao().removeAll();
2774
                        mAppDatabase.getCapsuleDao().removeAll();
2775
                        mAppDatabase.getTopicDao().removeAll();
2776
 
2777
 
2778
                        JSONObject data = objJSON.getJSONObject("data");
2779
                        syncFromServer(data);
2780
 
2781
 
2782
                    }
2783
 
2784
 
2785
                } catch (JSONException e) {
2786
                    Log.d(TAG, e.getMessage());
2787
                }
2788
 
2789
                reloadNavHeader();
2790
 
2791
 
2792
            }
2793
        });
2794
    }
2795
     */
2796
 
2797
 
2798
 
19 gabriel 2799
}