Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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