package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.cygnusa.hyperm.appupdater.AppUpdater;
import com.cygnusa.hyperm.droppy.DroppyMenuItem;
import com.cygnusa.hyperm.droppy.DroppyMenuPopup;
import com.cygnusa.hyperm.droppy.EasyDialog;
import com.cygnusa.hyperm.fancyshowcase.DismissListener;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.fragments.AssessmentListFragment;
import com.cygnusa.hyperm.fragments.EMICaluculatorFragment;
import com.cygnusa.hyperm.fragments.HomeFragment;
import com.cygnusa.hyperm.fragments.LeaderBoardFragment;
import com.cygnusa.hyperm.fragments.MyLearningFragment;
import com.cygnusa.hyperm.fragments.SurveyFragment;
import com.cygnusa.hyperm.library.AppUtils;
import com.cygnusa.hyperm.screenpinview.AppLockActivity;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CustomViewPager;
import com.cygnusa.hyperm.util.DepthPageTransformerNew;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.NotificationBadge;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AnswerResponse;
import com.cygnusa.hyperm.wrappers.AppVersion;
import com.cygnusa.hyperm.wrappers.Banner;
import com.cygnusa.hyperm.wrappers.BannerResponse;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.FragmentItem;
import com.cygnusa.hyperm.wrappers.HitCountModel;
import com.cygnusa.hyperm.wrappers.Notification;
import com.cygnusa.hyperm.wrappers.NotificationResponse;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import me.leolin.shortcutbadger.ShortcutBadger;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, DismissListener {

    public static Handler.Callback homeFragmentCallback;
    public static Handler.Callback callback, notificationCallback;
    public static Handler.Callback profileUpdateCallback;
    public static Handler.Callback badgeUpdateCallback;
    DrawerLayout drawer;
    Toolbar toolbar;
    NavigationView navigationView;
    ActionBarDrawerToggle toggle;
    boolean doubleBackToExitPressedOnce = false;
    FragmentManager fragmentManager;
    TransparentProgressDialog progressDialog;
    ApiService restService;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    NotificationBadge badge;
    View header;
    CustomViewPager viewPager;
    TextView headerTitle;
    DroppyMenuPopup droppyMenu;
    EasyDialog easyDialog;
    ImageView rightMenu;
    FrameLayout notificationButton;
    boolean canGoNotification = false;
    MainPagerAdapter viewPagerAdapter;
    ArrayList<FragmentItem> fragments = new ArrayList<>();
    private int SHOWCASE_POSITION = 0;
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;
    private LinearLayout menulayoutLogout;
    private LinearLayout menulayoutSettings;
    private LinearLayout menulayoutChangePassword;
    public static Handler.Callback learningPathcallback;
    private FirebaseAnalytics firebaseAnalytics;

    public static ArrayList<Banner> BANNERS = new ArrayList<>();
    Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        GlobalData.openDatabase(HomeActivity.this);
        setupWindowAnimations();

        badge = findViewById(R.id.badge);
        firebaseAnalytics = FirebaseAnalytics.getInstance(this);

        bundle = new Bundle();
        bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "1");
        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "HomeActivity");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

        toolbar = findViewById(R.id.toolbar);
        viewPager = findViewById(R.id.viewPager);

        menulayoutSettings = findViewById(R.id.layout1);
        menulayoutChangePassword = findViewById(R.id.layout2);
        menulayoutLogout = findViewById(R.id.layout3);

        rightMenu = findViewById(R.id.rightMenu);
        notificationButton = findViewById(R.id.notificationButton);
        headerTitle = findViewById(R.id.headerTitle);

        headerTitle.setOnClickListener(v -> {
            if (viewPager.getCurrentItem() != 0) {
                navigationView.getMenu().getItem(0).setChecked(true);
                viewPager.setCurrentItem(0, false);
                new Handler(HomeFragment.callback).sendEmptyMessage(0);
            }
        });

        menulayoutSettings.setOnClickListener(v -> {
            drawer.closeDrawer(GravityCompat.START);
            Intent i = new Intent(HomeActivity.this, SettingsActivity.class);
            i.putExtra("usertype", "dse");
            startActivity(i);
        });

        menulayoutChangePassword.setOnClickListener(v -> {
            drawer.closeDrawer(GravityCompat.START);
            startActivity(new Intent(HomeActivity.this, ChangePasswordActivity.class));
        });

        menulayoutLogout.setOnClickListener(v -> {
            drawer.closeDrawer(GravityCompat.START);
            new AlertDialog.Builder(HomeActivity.this)
                    .setMessage("Are you sure you want to logout?")
                    .setPositiveButton("Yes",
                            (dialog, which) -> {
//
                                bundle = new Bundle();
                                bundle.putString("Logout", "Logout");
                                firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                                getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                        .edit().putString("FCM_TOKEN_ID", "").apply();
                                GlobalData.sdb.delete("session", null, null);
                                GlobalData.sdb.delete("topic", null, null);
                                deleteLocalFiles();
                                startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                finish();
                            }).setNegativeButton("No", null).show();

        });


        canGoNotification = getIntent().getBooleanExtra("canGoNotification", false);
        setSupportActionBar(toolbar);
        drawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        restService = ((MainApplication) getApplication()).getClient();
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        if (drawer != null) {
            drawer.addDrawerListener(toggle);
        }
        toggle.syncState();
        toolbar.setContentInsetStartWithNavigation(0);

        fragmentManager = getSupportFragmentManager();
        if (StorePreference.getInstance(this).getBooleanValue(GlobalData.ISDSELOGIN))
            sendDashboardHitCount();

        /*---------------------------------Fragement----------------------------------*/
        FragmentItem homeItem = new FragmentItem();
        homeItem.setFragment(new HomeFragment());
        homeItem.setTitle("home");
        fragments.add(homeItem);

        FragmentItem myTrainingItem = new FragmentItem();
        myTrainingItem.setFragment(new MyLearningFragment());
        myTrainingItem.setTitle("My Learning");
        fragments.add(myTrainingItem);

        FragmentItem assessmentFragmentItem = new FragmentItem();
        assessmentFragmentItem.setFragment(new AssessmentListFragment());
        assessmentFragmentItem.setTitle("My Assessment");
        fragments.add(assessmentFragmentItem);

        FragmentItem leaderBoardFragmentItem = new FragmentItem();
        leaderBoardFragmentItem.setFragment(new LeaderBoardFragment());
        leaderBoardFragmentItem.setTitle("My Ranking");
        fragments.add(leaderBoardFragmentItem);

        FragmentItem feedbackFragmentItem = new FragmentItem();
        feedbackFragmentItem.setFragment(new SurveyFragment());
        feedbackFragmentItem.setTitle("Feedback");
        fragments.add(feedbackFragmentItem);

        FragmentItem emiFragmentItem = new FragmentItem();
        emiFragmentItem.setFragment(new EMICaluculatorFragment());
        emiFragmentItem.setTitle("EMI Calculator");
        fragments.add(emiFragmentItem);

        /*---------------------------------Fragement----------------------------------*/

        viewPagerAdapter = new MainPagerAdapter(fragmentManager, fragments);
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setPageTransformer(true, new DepthPageTransformerNew());
        checkPermission();

        navigationView.inflateMenu(R.menu.hyper_side_menu);
        navigationView.getMenu().getItem(0).setChecked(true);
        header = navigationView.getHeaderView(0);

        header.findViewById(R.id.editProfile).setOnClickListener(v -> {
            drawer.closeDrawer(GravityCompat.START);
            bundle = new Bundle();
            bundle.putString("Activity", "MyProfileActivity");
            firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
            startActivity(new Intent(HomeActivity.this, MyProfileActivity.class));
        });

        header.findViewById(R.id.userImage).setOnClickListener(v -> {
            drawer.closeDrawer(GravityCompat.START);
            bundle = new Bundle();
            bundle.putString("Activity", "MyProfileActivity");
            firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
            startActivity(new Intent(HomeActivity.this, MyProfileActivity.class));
        });

        header.findViewById(R.id.userName).setOnClickListener(v -> {
            drawer.closeDrawer(GravityCompat.START);
            bundle = new Bundle();
            bundle.putString("Activity", "MyProfileActivity");
            firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
            startActivity(new Intent(HomeActivity.this, MyProfileActivity.class));
        });

        profileUpdateCallback = msg -> {
            Glide.with(HomeActivity.this).load(GlobalData.user.getData().getProfile_photo())
                    .thumbnail(Glide.with(HomeActivity.this).load(R.drawable.placeholder))
                    .into((ImageView) header.findViewById(R.id.userImage));
            TextView textView = header.findViewById(R.id.userName);
            textView.setText(String.format("%s %s", GlobalData.user.getData().getFname(), GlobalData.user.getData().getLname()));
            return false;
        };

        try {
            if (GlobalData.user.getData().getProfile_photo() != null)
                Glide.with(this).load(GlobalData.user.getData().getProfile_photo())
                        .thumbnail(Glide.with(this).load(R.drawable.placeholder))
                        .into((ImageView) header.findViewById(R.id.userImage));


            TextView textView = header.findViewById(R.id.userName);
            TextView textUserRole = header.findViewById(R.id.userRole);
            textUserRole.setSelected(true);
            textView.setText(String.format("%s %s", GlobalData.user.getData().getFname(), GlobalData.user.getData().getLname()));
            textUserRole.setText(String.format("%s", GlobalData.user.getData().getRolename()));

            Display display = getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            GlobalData.width = size.x;
        } catch (Exception e) {
            e.printStackTrace();
        }
        initDroppyMenu();

        rightMenu.setOnClickListener(v -> {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                easyDialog = new EasyDialog(HomeActivity.this, droppyMenu)
                        .setLayout(droppyMenu.show())
                        .setGravity(EasyDialog.GRAVITY_BOTTOM)
                        .setBackgroundColor(Color.TRANSPARENT, Color.WHITE)
                        .setLocationByAttachedView(rightMenu)
                        .setAnimationTranslationShow(EasyDialog.DIRECTION_X, 350,
                                GlobalData.width, 0)
                        .setAnimationTranslationDismiss(EasyDialog.DIRECTION_X, 350, 0,
                                GlobalData.width).setTouchOutsideDismiss(true)
                        .setMatchParent(false).setMarginLeftAndRight(0, 15)
                        .setOutsideColor(Color.parseColor("#80000000")).show();
            }
        });

        notificationButton.setOnClickListener(v -> {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                goNotificationActivity();
            }
        });
        learningPathcallback = msg -> {
            new Handler(MyLearningFragment.callback).sendEmptyMessage(0);
            return false;
        };


        homeFragmentCallback = msg -> {
            switch (msg.what) {
                case 0:
                    navigationView.getMenu().getItem(1).setChecked(true);
                    viewPager.setCurrentItem(1, true);
                    bundle = new Bundle();
                    bundle.putString("Fragment", "MyTrainingFragment");
                    firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                    new Handler(MyLearningFragment.callback).sendEmptyMessage(0);
                    break;
                case 1:
                    navigationView.getMenu().getItem(2).setChecked(true);
                    viewPager.setCurrentItem(2, true);
                    bundle = new Bundle();
                    bundle.putString("Fragment", "AssessmentListFragment");
                    firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                    new Handler(AssessmentListFragment.callback).sendEmptyMessage(0);
                    break;
                case 2:
                    navigationView.getMenu().getItem(2).setChecked(true);
                    viewPager.setCurrentItem(2, true);

                    break;
                case 3:
                    navigationView.getMenu().getItem(4).setChecked(true);
                    viewPager.setCurrentItem(4, true);
                    bundle = new Bundle();
                    bundle.putString("Fragment", "SurveyFragment");
                    firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                    new Handler(SurveyFragment.callback).sendEmptyMessage(0);
                    break;

                case 4:
                    navigationView.getMenu().getItem(3).setChecked(true);
                    viewPager.setCurrentItem(3, true);
                    bundle = new Bundle();
                    bundle.putString("Fragment", "LeaderBoardFragment");
                    firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                    new Handler(LeaderBoardFragment.callback).sendEmptyMessage(0);
                    break;
                default:
                    break;
            }

            return false;
        };

        Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        headerTitle.setText("HYPER-M");
                        break;
                    case 1:
                        headerTitle.setText("My Learning");
                        break;

                    case 2:
                        headerTitle.setText("My Assessment");
                        break;
                    case 3:
                        headerTitle.setText("My Ranking");
                        break;
                    case 4:
                        headerTitle.setText("My Feedback");
                        break;
                    case 5:
                        headerTitle.setText("My Reward Points");
                        break;

                    case 6:
                        headerTitle.setText("Bulletin");
                        break;
                    case 7:
                        headerTitle.setText("EMI Calculator");
                        break;


                    default:
                        headerTitle.setText("HYPER-M");
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        getBanner();
        updateLocalAssessment();
        getNotifications();

        notificationCallback = msg -> {
            getNotifications();
            return false;
        };

        callback = msg -> {
            if (GlobalData.canLogout) {
                startActivity(new Intent(getBaseContext(), LoginActivity.class));
                finish();
            }
            return false;
        };

        badgeUpdateCallback = msg -> {
            getNotifications();
            return false;
        };

        new Handler().postDelayed(() -> {
            if (getPreferences(MODE_PRIVATE).getBoolean("HomeActivity", true)) {
                showHelpScreen();
                getPreferences(MODE_PRIVATE).edit().putBoolean("HomeActivity", false).apply();
            }
//                checkAppVersion();
        }, 1000);

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnSuccessListener(instanceIdResult -> updateFCMTokenToServer(instanceIdResult.getToken()));

        AppUpdater appUpdater = new AppUpdater(this);
        appUpdater.start();
    }


    private void sendDashboardHitCount() {

        restService.sendAllHitCount(buildConfigData()).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    Log.e("responeHitDashboard", response.body().getMessage());
                } else {
                    Log.e("responeHitDashboard", response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (t.getMessage() != null) {
                    Log.e("responeHitDashboard", t.getMessage());
                }
            }
        });
    }

    private HitCountModel buildConfigData() {
        HitCountModel hitCountModel = new HitCountModel();
        hitCountModel.setPage("Dashboard");
        return hitCountModel;
    }

    private void checkAppVersion() {
        if (new UtilService().isNetworkAvailable(HomeActivity.this)) {
            try {
                //String url = GlobalData.APP_URL + BuildConfig.APPLICATION_ID.trim() + "&deviceid=1";
                String url = GlobalData.APP_URL + GlobalData.AppId + "&deviceid=1";
                restService.getAppVersion(url).enqueue(new Callback<AppVersion>() {
                    @Override
                    public void onResponse(Call<AppVersion> call, Response<AppVersion> response) {
                        if (response.isSuccessful()) {
                            if (response.body() != null && response.body()
                                    .getCont().trim().equalsIgnoreCase("success")) {
                                int versionCode = AppUtils.getVersionCode(HomeActivity.this);
                                int iapkCode = Integer.parseInt(response.body().getVersioncode().trim());
                                if (iapkCode > versionCode) {
                                    showDialog(HomeActivity.this, response.body().getUrl().getAndroid(), iapkCode);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<AppVersion> call, Throwable t) {

                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showDialog(final Context context, final String apkUrl, final int apkCode) {
        File f = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null), ".HYPERM");
        if (!f.exists()) {
            f.mkdirs();
        }

        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM", "Apk");
        if (!f1.exists()) {
            f1.mkdirs();
        }

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(HomeActivity.this);
        builder.setMessage("New update for HYPERM App is available")
                .setPositiveButton(context.getResources().getString(R.string.alert_update),
                        (dialog, id) -> downloadFile(apkUrl, apkCode)).setNegativeButton("Cancel", null);

        android.app.AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void downloadFile(String url, int apkCode) {
        DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);
        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("HYPERM")
                .setDescription("Downloading...")
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setDestinationInExternalPublicDir("/.HYPERM/Apk", "hyperm_v_" + apkCode + ".apk");
        assert mgr != null;
        mgr.enqueue(request);
        registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            try {
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    String filePath = getDownloadedFilePath(ctxt, downloadId);
                    Intent intent1 = new Intent(Intent.ACTION_VIEW);
                    intent1.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            ctxt.unregisterReceiver(this);
        }
    };

    private String getDownloadedFilePath(Context context, long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        String result = "";
        Cursor c = null;
        try {
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            assert downloadManager != null;
            c = downloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                int fileUriIdx = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                String fileUri = c.getString(fileUriIdx);
                if (fileUri != null) {
                    File mFile = new File(Uri.parse(fileUri).getPath());
                    result = mFile.getAbsolutePath();
                }
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return result;
    }

    @SuppressLint("HardwareIds")
    private void updateFCMTokenToServer(String newRegId) {
        preferences = getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE);
        if (newRegId != null && !newRegId.trim().isEmpty()) {
            String oldid = preferences.getString("FCM_TOKEN_ID", "");
            if (!oldid.equals(newRegId)) {
                if (new UtilService().isNetworkAvailable(HomeActivity.this)) {

                    try {
                        String deviceId = Settings.Secure.getString(getApplicationContext()
                                .getContentResolver(), Settings.Secure.ANDROID_ID);
                        String manufacturer = Build.MANUFACTURER;
                        String model = Build.MODEL;
                        String version = Build.VERSION.RELEASE;
                        HashMap<String, String> map = new HashMap<>();
                        map.put("token", newRegId);
                        map.put("deviceid", deviceId);
                        map.put("devicetype", "android");
                        map.put("model", model);
                        map.put("manufacture", manufacturer);
                        map.put("version", version);
                        restService.updateFcmToken(map).enqueue(new MyCallback<ErrorResponse>(newRegId) {
                            @Override
                            public void onResponse(Call<ErrorResponse> call, Response<ErrorResponse> response) {
                                if (response.body() != null && response.body().getStatus() == 200) {
                                    bundle = new Bundle();
                                    bundle.putString("FCM_token", "FCM Token Updated");
                                    firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                                    preferences.edit().putString("FCM_TOKEN_ID", ids).apply();
                                }
                            }

                            @Override
                            public void onFailure(Call<ErrorResponse> call, Throwable t) {

                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void showHelpScreen() {
        bundle = new Bundle();
        bundle.putString("Screen", "HelpScreen");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

        try {
            if (viewPager.getCurrentItem() == 0) {
                SHOWCASE_POSITION = 0;
                new FancyShowCaseView.Builder(this)
                        .focusOn(getNavButtonView(toolbar))
                        .title("Tap here to access Sidebar Menu")
                        .titleSize(22, 1)
                        .closeOnTouch(true)
                        .focusShape(FocusShape.CIRCLE)
                        .dismissListener(this)
                        .backgroundColor(Color.parseColor("#99000000"))
                        .build()
                        .show();
            } else if (viewPager.getCurrentItem() == 1) {
                MyLearningFragment fragment = (MyLearningFragment) fragments.get(1).getFragment();
                fragment.showHelpScreen();
            } else if (viewPager.getCurrentItem() == 2) {

            } else if (viewPager.getCurrentItem() == 3) {
                AssessmentListFragment fragment = (AssessmentListFragment) fragments.get(3).getFragment();
                //fragment.showHelpScreen();
            } else if (viewPager.getCurrentItem() == 4) {
                LeaderBoardFragment fragment = (LeaderBoardFragment) fragments.get(4).getFragment();
                //   fragment.showHelpScreen();
            } else if (viewPager.getCurrentItem() == 5) {
                SurveyFragment fragment = (SurveyFragment) fragments.get(5).getFragment();
                // fragment.showHelpScreen();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDismiss(String id) {
        try {
            if (SHOWCASE_POSITION == 0) {
                new FancyShowCaseView.Builder(this)
                        .focusOn(notificationButton)
                        .title("Tap here to view Notification")
                        .titleSize(22, 1)
                        .closeOnTouch(true)
                        .focusShape(FocusShape.CIRCLE)
                        .dismissListener(this)
                        .backgroundColor(Color.parseColor("#99000000"))
                        .build()
                        .show();
            } else if (SHOWCASE_POSITION == 1) {
                new FancyShowCaseView.Builder(this)
                        .focusOn(rightMenu)
                        .title("Tap here access Context Menu")
                        .titleSize(22, 1)
                        .closeOnTouch(true)
                        .focusShape(FocusShape.CIRCLE)
                        .dismissListener(this)
                        .backgroundColor(Color.parseColor("#99000000"))
                        .build()
                        .show();
            } else if (SHOWCASE_POSITION == 2) {
                HomeFragment fr = (HomeFragment) fragments.get(0).getFragment();
                new FancyShowCaseView.Builder(this)
                        .focusOn(fr.getSlider())
                        .title("Swipe here to view banner images")
                        .titleSize(22, 1)
                        .closeOnTouch(true)
                        .focusShape(FocusShape.ROUNDED_RECTANGLE)
                        .dismissListener(this)
                        .backgroundColor(Color.parseColor("#99000000"))
                        .build()
                        .show();
            } else if (SHOWCASE_POSITION == 3) {
                HomeFragment fr = (HomeFragment) fragments.get(0).getFragment();
                new FancyShowCaseView.Builder(this)
                        .focusOn(fr.getMenuLayout())
                        .titleGravity(1)
                        .title("Tap here to access quick navigations")
                        .titleSize(22, 1)
                        .closeOnTouch(true)
                        .focusShape(FocusShape.ROUNDED_RECTANGLE)
                        .dismissListener(this)
                        .backgroundColor(Color.parseColor("#99000000"))
                        .build()
                        .show();
            }

            SHOWCASE_POSITION++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSkipped(String id) {

    }

    private ImageButton getNavButtonView(Toolbar toolbar) {
        try {
            Class<?> toolbarClass = Toolbar.class;
            Field navButtonField = toolbarClass.getDeclaredField("mNavButtonView");
            navButtonField.setAccessible(true);
            return (ImageButton) navButtonField.get(toolbar);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void updateLocalAssessment() {
        if (new UtilService().isNetworkAvailable(HomeActivity.this)) {
            Cursor cursor1 = GlobalData.sdb.rawQuery("select * from assessment_answer", null);
            if (cursor1.getCount() != 0) {
                cursor1.moveToFirst();
                HashMap<String, String> map;
                for (int i = 0; i < cursor1.getCount(); i++) {
                    Gson gson = new Gson();
                    map = gson.fromJson(
                            cursor1.getString(cursor1.getColumnIndex("assessment_answer")),
                            new TypeToken<HashMap<String, String>>() {
                            }.getType());
                    restService.postAssessment(cursor1.getString(cursor1.getColumnIndex("assessment_id")), map)
                            .enqueue(new MyCallback<AnswerResponse>(cursor1.getInt(cursor1.getColumnIndex("id"))) {
                                @Override
                                public void onResponse(Call<AnswerResponse> call, retrofit2.Response<AnswerResponse> response) {
                                    if (response.body() != null && response.body().getStatus() == 200) {
                                        bundle = new Bundle();
                                        bundle.putString("update_local_assessment", "Local Assessment Updated");
                                        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

                                        Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_answer where id=" + id, null);
                                        if (cursor.getCount() > 0) {
                                            cursor.moveToFirst();
                                            GlobalData.sdb.execSQL("delete from assessment_question where assessment_id='"
                                                    + cursor.getString(cursor.getColumnIndex("assessment_id"))
                                                    + "' and category_id='" + cursor.getString(cursor.getColumnIndex("category_id"))
                                                    + "' and training_id='" + cursor.getString(cursor.getColumnIndex("training_id")) + "'");

                                            GlobalData.sdb.execSQL("delete from assessment where assessment_id  ='"
                                                    + cursor.getString(cursor.getColumnIndex("assessment_id"))
                                                    + "' and category_id='" + cursor.getString(cursor.getColumnIndex("category_id"))
                                                    + "' and training_id='" + cursor.getString(cursor.getColumnIndex("training_id")) + "'");

                                            GlobalData.sdb.execSQL("delete from assessment_answer where id=" + id);
                                        }

                                    } else if (response.body() != null && response.body().getStatus() == 401) {
                                        GlobalData.canLogout = true;
                                        startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                        finish();
                                    } else if (response.body() != null) {
                                        GlobalData.sdb.execSQL("update assessment_answer set error='"
                                                + response.body().getMessage() + "' where id=" + id);
                                    } else if (response.errorBody() != null) {
                                        Gson gson = new Gson();
                                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                        GlobalData.sdb.execSQL("update assessment_answer set error='"
                                                + message.getMessage() + "' where id=" + id);
                                        if (message.getStatus() == 401) {
                                            GlobalData.canLogout = true;
                                            startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                            finish();
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<AnswerResponse> call, Throwable t) {
                                    bundle = new Bundle();
                                    bundle.putString("update_local_assessment", "Local Assessment Update Failed.");
                                    firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                                }
                            });
                    cursor1.moveToNext();
                }
            }
        }
    }


    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    private void goNotificationActivity() {
        bundle = new Bundle();
        bundle.putString("Activity", "NotificationActivity");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
        startActivity(new Intent(getBaseContext(), NotificationActivity.class));

    }

    private void initDroppyMenu() {
        DroppyMenuPopup.Builder droppyBuilder = new DroppyMenuPopup.Builder(
                HomeActivity.this, rightMenu);
        droppyBuilder.addMenuItem(new DroppyMenuItem("Change Password", R.mipmap.icon_change_password))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("Settings", R.mipmap.icon_settings))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("FAQs", R.mipmap.icon_faq))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("About", R.mipmap.icon_about))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("Logout", R.mipmap.icon_logout))
                .addSeparator()
                .triggerOnAnchorClick(false);
        droppyBuilder.setOnClick((v, id) -> {
            easyDialog.dismiss();
            switch (id) {
                case 0:
                    new Handler().postDelayed(() -> {
                        bundle = new Bundle();
                        bundle.putString("Activity", "ChangePasswordActivity");
                        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                        startActivity(new Intent(HomeActivity.this, ChangePasswordActivity.class));
                    }, 300);
                    break;
                case 1:
                    new Handler().postDelayed(() -> {
                        bundle = new Bundle();
                        bundle.putString("Activity", "SettingsActivity");
                        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                        Intent i = new Intent(HomeActivity.this, SettingsActivity.class);
                        i.putExtra("usertype", "dse");
                        startActivity(i);
                    }, 300);
                    break;
                case 2:
                    new Handler().postDelayed(() -> {
                        bundle = new Bundle();
                        bundle.putString("Activity", "FaqActivity");
                        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                        startActivity(new Intent(HomeActivity.this, FaqActivity.class));
                    }, 300);
                    break;
                case 3:
                    new Handler().postDelayed(() -> {
                        bundle = new Bundle();
                        bundle.putString("Activity", "AboutActivity");
                        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
                        startActivity(new Intent(HomeActivity.this, AboutActivity.class));
                    }, 300);
                    break;
                case 4:
                    drawer.closeDrawer(GravityCompat.START);
                    new AlertDialog.Builder(HomeActivity.this)
                            .setMessage("Are you sure you want to logout?")
                            .setPositiveButton("Yes",
                                    (dialog, which) -> {
//                                                preferences = getSharedPreferences("UserDetails",
//                                                        Context.MODE_PRIVATE);
//                                                editor = preferences.edit();
//                                                editor.putString("inputUsername", null);
//                                                editor.putString("inputPassword", null);
//                                                editor.apply();
                                        getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                                .edit().putString("FCM_TOKEN_ID", "").apply();
                                        GlobalData.sdb.delete("session", null, null);
                                        GlobalData.sdb.delete("topic", null, null);
                                        deleteLocalFiles();
                                        startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                        finish();
                                    }).setNegativeButton("No", null).show();
                    break;

            }
        });
        droppyMenu = droppyBuilder.build();
    }

    public void deleteLocalFiles() {
        String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                + "/" + ".HYPERM/VIDEO";
        File dir = new File(fileName);
        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children != null && children.length > 0)
                for (String aChildren : children) {
                    new File(dir, aChildren).delete();
                }
        }
        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM", "PDF");
        if (f1.isDirectory()) {
            String[] children = dir.list();
            if (children != null && children.length > 0)
                for (int i = 0; i < children.length; i++) {
                    new File(dir, children[i]).delete();
                }

        }
    }


    private void getBanner() {
        if (new UtilService().isNetworkAvailable(HomeActivity.this)) {
            progressDialog = new TransparentProgressDialog(HomeActivity.this);
            progressDialog.show();

            try {
                restService.getBanner().enqueue(new Callback<BannerResponse>() {
                    @Override
                    public void onResponse(Call<BannerResponse> call, Response<BannerResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            GlobalData.BANNERS = response.body().getData();
                            if (GlobalData.BANNERS == null) {
                                GlobalData.BANNERS = new ArrayList<>();
                            }
                            Gson gson = new Gson();
                            JsonElement jsonElement = gson.toJsonTree(
                                    GlobalData.BANNERS, new TypeToken<ArrayList<Banner>>() {
                                    }.getType());
                            ContentValues values = new ContentValues();
                            values.put("banner", jsonElement.toString());
                            GlobalData.sdb.insert("banner", null, values);

                            new Handler(HomeFragment.callback).sendEmptyMessage(0);
                            if (canGoNotification) {
                                goNotificationActivity();
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            startActivity(new Intent(getBaseContext(), LoginActivity.class));
                            finish();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                finish();
                            }
                        } else {
                            checkBannerDataInLocal();
                        }
                    }

                    @Override
                    public void onFailure(Call<BannerResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        checkBannerDataInLocal();
                    }
                });

            } catch (Exception e) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                checkBannerDataInLocal();
            }
        } else {
            checkBannerDataInLocal();
        }
    }

    private void checkBannerDataInLocal() {

        new Handler().postDelayed(() -> {
            Cursor cursor = GlobalData.sdb.rawQuery("select * from banner", null);
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                Gson gson = new Gson();
                GlobalData.BANNERS = gson.fromJson(
                        cursor.getString(cursor.getColumnIndex("banner")),
                        new TypeToken<ArrayList<Banner>>() {
                        }.getType());
                if (GlobalData.BANNERS == null) {
                    GlobalData.BANNERS = new ArrayList<>();
                }
                new Handler(HomeFragment.callback).sendEmptyMessage(0);
                if (canGoNotification) {
                    goNotificationActivity();
                }
            }
        }, 1000);

    }


    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (viewPager.getCurrentItem() != 0) {
            navigationView.getMenu().getItem(0).setChecked(true);
            viewPager.setCurrentItem(0, false);
            new Handler(HomeFragment.callback).sendEmptyMessage(0);
        } else {
            if (doubleBackToExitPressedOnce) {
                finish();
                this.overridePendingTransition(R.anim.animation_f_enter,
                        R.anim.animation_f_leave);
                return;
            }
            doubleBackToExitPressedOnce = true;
            GlobalData.showToast(this, "Press again to exit", Toast.LENGTH_SHORT).show();

            new Handler().postDelayed(() -> doubleBackToExitPressedOnce = false, 2000);
        }
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        drawer.closeDrawer(GravityCompat.START);

        if (id == R.id.home_menu) {
            viewPager.setCurrentItem(0, true);
            new Handler(HomeFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.myLearning) {
            viewPager.setCurrentItem(1, true);
            new Handler(MyLearningFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.myAssessment) {
            viewPager.setCurrentItem(2, true);
            new Handler(AssessmentListFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.certification) {
//            viewPager.setCurrentItem(3, true);
//            new Handler(LeaderBoardFragment.callback).sendEmptyMessage(0);
            startActivity(new Intent(this, MyCertificationActivity.class));
        } else if (id == R.id.myDiscuss) {
//            viewPager.setCurrentItem(4, true);
//            new Handler(SurveyFragment.callback).sendEmptyMessage(0);
            startActivity(new Intent(this, BlogActivity.class));
        } else if (id == R.id.myRanking) {
//            viewPager.setCurrentItem(4, true);
//            new Handler(SurveyFragment.callback).sendEmptyMessage(0);
            startActivity(new Intent(this, MyHyperRanking.class));
        } else if (id == R.id.myRewardPoints) {
            startActivity(new Intent(this, MyEarnedPoints.class));
        } else if (id == R.id.myBulletin) {
            startActivity(new Intent(this, BulletinActivity.class));
        } else if (id == R.id.mySchedule) {
            //startActivity(new Intent(this, ScheduleListActivity.class));
        } else if (id == R.id.myTraining) {
            if (GlobalData.user.getData().getRole().equalsIgnoreCase("10")) {
                startActivity(new Intent(this, ClassRoomDSETainingActivity.class));
            } else {
                startActivity(new Intent(this, ClassRoomTrainerTainingActivity.class));
            }
        } else if (id == R.id.trainingQR) {
            startActivity(new Intent(this, ShowQrCodeClass.class));
        } else if (id == R.id.emi_calc) {
            if (viewPager.getCurrentItem() != 7) {
                viewPager.setCurrentItem(7, true);
            }
            headerTitle.setText("EMI Calculator");
            ((EMICaluculatorFragment) fragments.get(5).getFragment()).onResumeFragment(GlobalData.EMI_URL);

        } else if (id == R.id.myWallet) {
            if (GlobalData.user.getData().getMpin().trim().isEmpty()) {
                Intent i = new Intent(HomeActivity.this, OtpActivity.class);
                i.putExtra("type", "menu");
                startActivity(i);
            } else {
                startActivity(new Intent(this, AppLockActivity.class));
            }

        } else if (id == R.id.rotate) {
            startActivity(new Intent(this, ProductExplorerActivity.class));
        }

        return true;
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            ArrayList<String> listPermissionsNeeded = new ArrayList<>();
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                listPermissionsNeeded
                        .add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                listPermissionsNeeded
                        .add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            if (checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED) {
                listPermissionsNeeded
                        .add(android.Manifest.permission.RECORD_AUDIO);
            }

            if (checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
                listPermissionsNeeded
                        .add(android.Manifest.permission.CAMERA);
            }

            if (!listPermissionsNeeded.isEmpty())
                ActivityCompat.requestPermissions(this, listPermissionsNeeded
                        .toArray(new String[listPermissionsNeeded.size()]), 1);

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (viewPager != null) {
                switch (viewPager.getCurrentItem()) {
                    case 0:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 1:
                        ((MyLearningFragment) viewPagerAdapter.getItem(1)).onResumeFragment();
                        break;
                    case 2:
                        ((AssessmentListFragment) viewPagerAdapter.getItem(2)).onResumeFragment();
                        break;
                    case 3:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 4:
                        ((SurveyFragment) viewPagerAdapter.getItem(4)).onResumeFragment();
                        break;
                    case 5:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 6:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (GlobalData.canLogout) {
            startActivity(new Intent(getBaseContext(), LoginActivity.class));
            finish();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        try {
            if (viewPager != null) {
                switch (viewPager.getCurrentItem()) {
                    case 0:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 1:
                        ((MyLearningFragment) viewPagerAdapter.getItem(1)).onResumeFragment();
                        break;
                    case 2:
                        ((AssessmentListFragment) viewPagerAdapter.getItem(2)).onResumeFragment();
                        break;
                    case 3:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 4:
                        ((SurveyFragment) viewPagerAdapter.getItem(4)).onResumeFragment();
                        break;
                    case 5:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 6:
                        ((HomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (GlobalData.canLogout) {
            startActivity(new Intent(getBaseContext(), LoginActivity.class));
            finish();
        }
    }

    private void getNotifications() {
        if (new UtilService().isNetworkAvailable(HomeActivity.this)) {
            restService.getNotificationsDB().enqueue(new Callback<NotificationResponse>() {
                @Override
                public void onResponse(Call<NotificationResponse> call, Response<NotificationResponse> response) {
                    if (response.body() != null && response.body().getStatus() == 200) {

                        int count = 0;
                        try {
                            count = Integer.parseInt(response.body().getNot_read_count());

                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        badge.setNumber(count);
                        try {
                            ShortcutBadger.applyCount(HomeActivity.this, count);
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                    }
                }

                @Override
                public void onFailure(Call<NotificationResponse> call, Throwable t) {
                    Log.e("rr", t.toString());
                }
            });
        } else {
            Cursor cursor = GlobalData.sdb.rawQuery("select * from notifications", null);
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                Gson gson = new Gson();
                ArrayList<Notification> notifications = gson.fromJson(
                        cursor.getString(cursor.getColumnIndex("notifications")),
                        new TypeToken<ArrayList<Notification>>() {
                        }.getType());
                int cnt = 0;
                for (Notification notification : notifications) {
                    if (notification.getStatus().trim().equalsIgnoreCase("0")) {
                        cnt++;
                    }
                }
                badge.setNumber(cnt);
                try {
                    ShortcutBadger.applyCount(HomeActivity.this, cnt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public class MainPagerAdapter extends FragmentStatePagerAdapter {

        ArrayList<FragmentItem> fragments = new ArrayList<>();

        private MainPagerAdapter(FragmentManager fm, ArrayList<FragmentItem> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position).getFragment();
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return fragments.get(position).getTitle();
        }
    }

    @SuppressLint("StaticFieldLeak")
    private class AppUpdaterTask extends AsyncTask<Void, Integer, Integer> {

        String apkUrl;
        int apkCode;
        String fileName;

        private AppUpdaterTask(String apkUrl, int apkCode) {
            this.apkUrl = apkUrl;
            this.apkCode = apkCode;
            mBuilder.setProgress(100, 0, false);
            mNotifyManager.notify(1, mBuilder.build());
        }

        @Override
        protected void onPreExecute() {
            GlobalData.showToast(HomeActivity.this, "Updating..", Toast.LENGTH_LONG);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (values[0] % 5 == 0) {
                CharSequence title = "Downloading: " + values[0] + "%";
                mBuilder.setContentTitle(title);
                mBuilder.setProgress(100, values[0], false);
                mNotifyManager.notify(1, mBuilder.build());
                super.onProgressUpdate(values);
            }
        }

        @Override
        protected Integer doInBackground(Void... params) {
            OutputStream output = null;
            InputStream input = null;
            try {
                int count;
                URL url = new URL(apkUrl);
                URLConnection conection = url.openConnection();
                conection.connect();
                int lenghtOfFile = conection.getContentLength();
                input = new BufferedInputStream(url.openStream(),
                        8192);
                fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                        + "/" + ".HYPERM/Apk/hyperm_v_" + apkCode + ".apk";
                output = new FileOutputStream(fileName);
                byte[] data = new byte[1024];
                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress((int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }
                output.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    output.close();
                    input.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            mBuilder.setContentTitle("Download complete");
            mBuilder.setProgress(0, 0, false);
            mNotifyManager.notify(1, mBuilder.build());

            new Handler().postDelayed(() -> {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri apkURI = FileProvider.getUriForFile(
                        HomeActivity.this,
                        HomeActivity.this.getApplicationContext()
                                .getPackageName() + ".provider", new File(fileName));
                install.setDataAndType(apkURI, "application/vnd.android.package-archive");
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(install);
                finishAffinity();
            }, 2000);
        }
    }
}