package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
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.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
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.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.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.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.appupdater.AppUpdater;
import com.cygnusa.hyperm.droppy.DroppyClickCallbackInterface;
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.AMHomeFragment;
import com.cygnusa.hyperm.fragments.AMSalesFragment;
import com.cygnusa.hyperm.fragments.AmTeamMyRankingFragment;
import com.cygnusa.hyperm.fragments.AssessmentListFragment;
import com.cygnusa.hyperm.fragments.EMICaluculatorFragment;
import com.cygnusa.hyperm.fragments.HomeFragment;
import com.cygnusa.hyperm.fragments.MyLearningFragment;
import com.cygnusa.hyperm.fragments.TeamRankingFragment;
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.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AnswerResponse;
import com.cygnusa.hyperm.wrappers.Banner;
import com.cygnusa.hyperm.wrappers.BannerResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.FragmentItem;
import com.cygnusa.hyperm.wrappers.Notification;
import com.cygnusa.hyperm.wrappers.NotificationResponse;

import java.io.File;
import java.lang.reflect.Field;
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;

import static com.cygnusa.hyperm.BulletinActivity.isFromAMHome;


public class AMHomeActivity 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;
    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;
    public static Handler.Callback learningPathcallback;
    private String role = "";

    String[] arrReportsUrl = {"salesreport/mobile/", "dsereport/mobile/", "assessmentreport/mobile/",
            "leaderboardreport/mobile/", "asessmentleaderboardreport/mobile/", "analyticalreport/mobile/",
            "coursereport/mobile/", "feedbackreport/mobile/"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);
        GlobalData.openDatabase(AMHomeActivity.this);
        setupWindowAnimations();
        badge = findViewById(R.id.badge);
        toolbar = findViewById(R.id.toolbar);
        viewPager = findViewById(R.id.viewPager);
        rightMenu = findViewById(R.id.rightMenu);
        rightMenu = findViewById(R.id.rightMenu);
        notificationButton = findViewById(R.id.notificationButton);
        headerTitle = findViewById(R.id.headerTitle);
        headerTitle.setSelected(true);
        headerTitle.setOnClickListener(v -> {
            if (viewPager.getCurrentItem() != 0) {
                navigationView.getMenu().getItem(0).setChecked(true);
                viewPager.setCurrentItem(0, false);
                new Handler(HomeFragment.callback).sendEmptyMessage(0);
            }
        });

        findViewById(R.id.layout1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.closeDrawer(GravityCompat.START);
                Intent i = new Intent(AMHomeActivity.this, SettingsActivity.class);
                i.putExtra("usertype", "am");
                startActivity(i);
            }
        });

        findViewById(R.id.layout2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.closeDrawer(GravityCompat.START);
                startActivity(new Intent(AMHomeActivity.this, ChangePasswordActivity.class));
            }
        });

        findViewById(R.id.layout3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.closeDrawer(GravityCompat.START);
                new AlertDialog.Builder(AMHomeActivity.this)
                        .setMessage("Are you sure you want to logout?")
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                                .edit().putString("FCM_TOKEN_ID", "").apply();
                                        GlobalData.sdb.delete("session", null, null);
                                        GlobalData.zmEmail = "none";
                                        GlobalData.rmEmail = "none";
                                        GlobalData.amEmail = "none";
                                        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();
        FragmentItem homeItem = new FragmentItem();
        homeItem.setFragment(new AMHomeFragment());
        homeItem.setTitle("home");
        fragments.add(homeItem);

        FragmentItem mySalesItem = new FragmentItem();
        mySalesItem.setFragment(new AMSalesFragment());
        mySalesItem.setTitle("Sales");
        fragments.add(mySalesItem);

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

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

        FragmentItem teamLeaderBoardFragmentItem = new FragmentItem();
        teamLeaderBoardFragmentItem.setFragment(new TeamRankingFragment());
        teamLeaderBoardFragmentItem.setTitle("Team Ranking");
        fragments.add(teamLeaderBoardFragmentItem);

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

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

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

        try {
            role = GlobalData.user.getData().getRole();
            if (role.equalsIgnoreCase("3")) {
                navigationView.inflateMenu(R.menu.side_menu_ho);
            } else if (role.equalsIgnoreCase("4")
                    || role.equalsIgnoreCase("6")) {
                navigationView.inflateMenu(R.menu.side_menu_tr_zm_rm);
            } else if (role.equalsIgnoreCase("7")) {
                navigationView.inflateMenu(R.menu.side_menu_am);
            } else if (role.equalsIgnoreCase("5")) {
                navigationView.inflateMenu(R.menu.side_menu_trainer);
            } else if (role.equalsIgnoreCase("14")) {
                navigationView.inflateMenu(R.menu.side_menu_de);
            } else {
                navigationView.inflateMenu(R.menu.side_menu);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        navigationView.getMenu().getItem(0).setChecked(true);
        header = navigationView.getHeaderView(0);

        header.findViewById(R.id.editProfile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.closeDrawer(GravityCompat.START);
                startActivity(new Intent(AMHomeActivity.this, MyProfileActivity.class));
            }
        });
        header.findViewById(R.id.userImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.closeDrawer(GravityCompat.START);
                startActivity(new Intent(AMHomeActivity.this, MyProfileActivity.class));
            }
        });
        header.findViewById(R.id.userName).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.closeDrawer(GravityCompat.START);
                startActivity(new Intent(AMHomeActivity.this, MyProfileActivity.class));
            }
        });
        profileUpdateCallback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                Glide.with(AMHomeActivity.this).load(GlobalData.user.getData().getProfile_photo())
                        .thumbnail(Glide.with(AMHomeActivity.this).load(R.drawable.gif_loader))
                        .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;
            }
        };


        homeFragmentCallback = new Handler.Callback() {
            @SuppressLint("SetTextI18n")
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        if (role.equalsIgnoreCase("7")) {
                            navigationView.getMenu().getItem(6).setChecked(true);
                            headerTitle.setText("Sales");
                        } else if (role.equalsIgnoreCase("4") || role.equalsIgnoreCase("6")) {
                            navigationView.getMenu().getItem(5).setChecked(true);
                            headerTitle.setText("Sales");
                        } else if (role.equalsIgnoreCase("5")) {
                            navigationView.getMenu().getItem(6).setChecked(true);
                            headerTitle.setText("Sales");
                        } else if (role.equalsIgnoreCase("3")) {
                            navigationView.getMenu().getItem(2).setChecked(true);
                            headerTitle.setText("Sales");
                        }
                        if (viewPager.getCurrentItem() != 1) {
                            viewPager.setCurrentItem(1, true);
                        }
                        ((AMSalesFragment) fragments.get(1).getFragment()).
                                onResumeFragment(arrReportsUrl[0] + GlobalData.user.getData().getEmailid().trim() + "/" +
                                        GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/" +
                                        AMHomeFragment.monthValue + "/" + AMHomeFragment.yearValue + "/");

                        break;
                    case 2:


                        if (role.equalsIgnoreCase("7")) {
                            navigationView.getMenu().getItem(7).setChecked(true);
                            headerTitle.setText("Certified Dse");
                        } else if (role.equalsIgnoreCase("4") || role.equalsIgnoreCase("6")) {
                            navigationView.getMenu().getItem(6).setChecked(true);
                            headerTitle.setText("Certified Dse");
                        } else if (role.equalsIgnoreCase("5")) {
                            navigationView.getMenu().getItem(7).setChecked(true);
                            headerTitle.setText("Certified Dse");
                        } else if (role.equalsIgnoreCase("3")) {
                            navigationView.getMenu().getItem(3).setChecked(true);
                            headerTitle.setText("Certified Dse");
                        }

                        if (viewPager.getCurrentItem() != 1) {
                            viewPager.setCurrentItem(1, true);
                        }
                        ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[1] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
                        break;
                    case 3:
                        if (role.equalsIgnoreCase("7")) {
                            navigationView.getMenu().getItem(8).setChecked(true);
                            headerTitle.setText("Assessment Reports");
                        } else if (role.equalsIgnoreCase("4") || role.equalsIgnoreCase("6")) {
                            navigationView.getMenu().getItem(7).setChecked(true);
                            headerTitle.setText("Assessment Reports");
                        } else if (role.equalsIgnoreCase("5")) {
                            navigationView.getMenu().getItem(8).setChecked(true);
                            headerTitle.setText("Assessment Reports");
                        } else if (role.equalsIgnoreCase("3")) {
                            navigationView.getMenu().getItem(4).setChecked(true);
                            headerTitle.setText("Assessment Reports");
                        }

                        if (viewPager.getCurrentItem() != 1) {
                            viewPager.setCurrentItem(1, true);
                        }
                        ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[2] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
                        break;
                    case 4:
                        navigationView.getMenu().getItem(6).setChecked(true);
                        headerTitle.setText("Ranking Sales");
                        if (viewPager.getCurrentItem() != 1) {
                            viewPager.setCurrentItem(1, true);
                        }
                        ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[3] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
                        break;
                    case 5:

                        if (role.equalsIgnoreCase("7")) {
                            navigationView.getMenu().getItem(4).setChecked(true);
                            headerTitle.setText("My Ranking");
                        } else if (role.equalsIgnoreCase("4") || role.equalsIgnoreCase("6")) {
                            navigationView.getMenu().getItem(3).setChecked(true);
                            headerTitle.setText("My Ranking");
                        } else if (role.equalsIgnoreCase("5")) {
                            navigationView.getMenu().getItem(4).setChecked(true);
                            headerTitle.setText("My Ranking");
                        }
                        viewPager.setCurrentItem(3, true);
                        new Handler(AmTeamMyRankingFragment.callback).sendEmptyMessage(0);
                        break;
                    case 6:

                        if (role.equalsIgnoreCase("7")) {
                            navigationView.getMenu().getItem(5).setChecked(true);
                            headerTitle.setText("Team Ranking");
                        } else if (role.equalsIgnoreCase("4") || role.equalsIgnoreCase("6")) {
                            navigationView.getMenu().getItem(4).setChecked(true);
                            headerTitle.setText("Team Ranking");
                        } else if (role.equalsIgnoreCase("5")) {
                            navigationView.getMenu().getItem(5).setChecked(true);
                            headerTitle.setText("Team Ranking");
                        } else if (role.equalsIgnoreCase("3")) {
                            navigationView.getMenu().getItem(1).setChecked(true);
                            headerTitle.setText("Team Ranking");
                        }

                        viewPager.setCurrentItem(4, true);
                        new Handler(TeamRankingFragment.callback).sendEmptyMessage(0);
                        break;

                    default:
                        break;
                }
                return false;
            }
        };
        Glide.with(this).load(GlobalData.user.getData().getProfile_photo())
                .thumbnail(Glide.with(this).load(R.drawable.gif_loader))
                .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;
        initDroppyMenu();
        rightMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (drawer.isDrawerOpen(GravityCompat.START)) {
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    easyDialog = new EasyDialog(AMHomeActivity.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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (drawer.isDrawerOpen(GravityCompat.START)) {
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    goNotificationActivity();
                }
            }
        });
        learningPathcallback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                new Handler(MyLearningFragment.callback).sendEmptyMessage(0);
                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) {
                if (position == 0) {
                    headerTitle.setText("Hyper-M");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        getBanner();
        updateLocalAssessment();
        getNotifications();
        notificationCallback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                getNotifications();
                return false;
            }
        };

        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (GlobalData.canLogout) {
                    GlobalData.zmEmail = "none";
                    GlobalData.rmEmail = "none";
                    GlobalData.amEmail = "none";
                    startActivity(new Intent(getBaseContext(), LoginActivity.class));
                    finish();
                }
                return false;
            }
        };

        badgeUpdateCallback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                getNotifications();
                return false;
            }
        };

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getPreferences(MODE_PRIVATE).getBoolean("HomeActivity", true)) {
                    showHelpScreen();
                    getPreferences(MODE_PRIVATE).edit().putBoolean("HomeActivity", false).apply();
                }
//                checkAppVersion();
            }
        }, 1000);

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
                    @Override
                    public void onSuccess(InstanceIdResult instanceIdResult) {
                        updateFCMTokenToServer(instanceIdResult.getToken());
                    }
                });

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

    }

//    private void checkAppVersion() {
//        if (new UtilService().isNetworkAvailable(AMHomeActivity.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 && Objects.requireNonNull(response.body())
//                                    .getCont().trim().equalsIgnoreCase("success")) {
//                                int versionCode = AppUtils.getVersionCode(AMHomeActivity.this);
//                                int iapkCode = Integer.parseInt(Objects.requireNonNull(response.body()).getVersioncode().trim());
//                                if (iapkCode > versionCode) {
//                                    showDialog(AMHomeActivity.this, Objects.requireNonNull(response.body()).getUrl().getAndroid(), iapkCode);
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Call<AppVersion> call, Throwable t) {
//
//                    }
//                });
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }


    private void showDialog(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(AMHomeActivity.this);
        builder.setMessage("New update for HYPER-M App is available")
                .setPositiveButton(context.getResources().getString(R.string.alert_update),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                downloadFile(apkUrl, apkCode);
                            }
                        }).setNegativeButton("Cancel", null);

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

    @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", "");
            assert oldid != null;
            if (!oldid.equals(newRegId)) {
                if (new UtilService().isNetworkAvailable(AMHomeActivity.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 && Objects.requireNonNull(response.body()).getStatus() == 200) {
                                    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() {
        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) {
                AMSalesFragment fragment = (AMSalesFragment) fragments.get(1).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) {
                AMHomeFragment fr = (AMHomeFragment) 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) {
                AMHomeFragment fr = (AMHomeFragment) fragments.get(0).getFragment();
                new FancyShowCaseView.Builder(this)
                        .focusOn(fr.getMenuLayout())
                        .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(AMHomeActivity.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, Response<AnswerResponse> response) {

                                    if (response.body() != null && Objects.requireNonNull(response.body()).getStatus() == 200) {
                                        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 && Objects.requireNonNull(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='"
                                                + Objects.requireNonNull(response.body()).getMessage() + "' where id=" + id);
                                    } else if (response.errorBody() != null) {
                                        Gson gson = new Gson();
                                        ErrorResponse message = gson.fromJson(Objects.requireNonNull(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) {

                                }
                            });
                    cursor1.moveToNext();
                }
            }
        }
    }


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

    private void goNotificationActivity() {
        startActivity(new Intent(getBaseContext(), NotificationActivity.class));
    }

    private void initDroppyMenu() {
        DroppyMenuPopup.Builder droppyBuilder = new DroppyMenuPopup.Builder(
                AMHomeActivity.this, rightMenu);
        droppyBuilder.addMenuItem(new DroppyMenuItem("Change Password"))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("Settings"))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("FAQs"))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("About"))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("Help"))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("Logout"))
                .addSeparator()
                .triggerOnAnchorClick(false);
        droppyBuilder.setOnClick(new DroppyClickCallbackInterface() {
            @Override
            public void call(View v, int id) {
                easyDialog.dismiss();

                switch (id) {

                    case 0:
                        startActivity(new Intent(AMHomeActivity.this, ChangePasswordActivity.class));
                        break;
                    case 1:
                        Intent i = new Intent(AMHomeActivity.this, SettingsActivity.class);
                        i.putExtra("usertype", "am");
                        startActivity(i);
                        break;
                    case 2:
                        startActivity(new Intent(AMHomeActivity.this, FaqActivity.class));
                        break;
                    case 3:
                        startActivity(new Intent(AMHomeActivity.this, AboutActivity.class));
                        break;
                    case 4:
                        showHelpScreen();
                        break;
                    case 5:
                        drawer.closeDrawer(GravityCompat.START);
                        new AlertDialog.Builder(AMHomeActivity.this)
                                .setMessage("Are you sure you want to logout?")
                                .setPositiveButton("Yes",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int 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.zmEmail = "none";
                                                GlobalData.rmEmail = "none";
                                                GlobalData.amEmail = "none";
                                                startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                                finish();
                                            }
                                        }).setNegativeButton("No", null).show();
                        break;

                }


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

    private void getBanner() {
        if (new UtilService().isNetworkAvailable(AMHomeActivity.this)) {
            progressDialog = new TransparentProgressDialog(AMHomeActivity.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 && Objects.requireNonNull(response.body()).getStatus() == 200) {
                            GlobalData.BANNERS = Objects.requireNonNull(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(AMHomeFragment.callback).sendEmptyMessage(0);
                            if (canGoNotification) {
                                goNotificationActivity();
                            }
                        } else if (response.body() != null && Objects.requireNonNull(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(Objects.requireNonNull(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(new Runnable() {
            @Override
            public void run() {
                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(AMHomeFragment.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(AMHomeFragment.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(new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        }
    }


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

        if (id == R.id.home_menu) {
            headerTitle.setText("HYPER-M");
            viewPager.setCurrentItem(0, true);
            new Handler(AMHomeFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.myBulletin) {
            isFromAMHome = true;
            startActivity(new Intent(this, BulletinActivity.class));
        } else if (id == R.id.mySchedule) {
          //  startActivity(new Intent(this, ScheduleListActivity.class));
        } else if (id == R.id.myTraining) {
            headerTitle.setText("My Learning");
            if (viewPager.getCurrentItem() != 5) {
                viewPager.setCurrentItem(5, true);
            }
            new Handler(MyLearningFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.mySales) {
            headerTitle.setText("Sales");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[0] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/" + AMHomeFragment.monthValue + "/" + AMHomeFragment.yearValue + "/");
        } else if (id == R.id.myDSE) {
            headerTitle.setText("Certified Dse");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[1] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
        } else if (id == R.id.myAssessment) {
            headerTitle.setText("Assessment Reports");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[2] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
        } else if (id == R.id.myLeaderBoardSales) {
            headerTitle.setText("My Ranking");
            if (viewPager.getCurrentItem() != 3) {
                viewPager.setCurrentItem(3, true);
            }
            new Handler(AmTeamMyRankingFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.myLeaderBoardAssessment) {
            headerTitle.setText("Team Ranking");
            if (viewPager.getCurrentItem() != 4) {
                viewPager.setCurrentItem(4, true);
            }
            new Handler(TeamRankingFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.myAnalyticReport) {
            headerTitle.setText("User Report");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[5] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
        } else if (id == R.id.myCourseReports) {
            headerTitle.setText("Course Completion");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[6] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
        } else if (id == R.id.myFeedbackReports) {
            headerTitle.setText("Feedback Report");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment(arrReportsUrl[7] + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
        } else if (id == R.id.mySalesReport) {
            headerTitle.setText("Set Sales Target");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment("setsalesreport/mobile/" + GlobalData.user.getData().getEmailid().trim() + "/" + GlobalData.zmEmail + "/" + GlobalData.rmEmail + "/" + GlobalData.amEmail + "/");
        } else if (id == R.id.training) {
            headerTitle.setText("Training");
            if (viewPager.getCurrentItem() != 1) {
                viewPager.setCurrentItem(1, true);
            }
            ((AMSalesFragment) fragments.get(1).getFragment()).onResumeFragment("trainer/mobile/" + GlobalData.user.getData().getEmailid().trim() + "/");

        } else if (id == R.id.assessment) {
            headerTitle.setText("My Assessment");
            viewPager.setCurrentItem(2, true);
            new Handler(AssessmentListFragment.callback).sendEmptyMessage(0);
        } else if (id == R.id.myFaq) {
            startActivity(new Intent(this, FaqActivity.class));
        } else if (id == R.id.myTrainingModule) {
            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(6).getFragment()).onResumeFragment(GlobalData.EMI_URL);

        } 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[0]), 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:
                        ((AMHomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 2:
                        ((AssessmentListFragment) viewPagerAdapter.getItem(2)).onResumeFragment();
                        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:
                        ((AMHomeFragment) viewPagerAdapter.getItem(0)).onResumeFragment();
                        break;
                    case 2:
                        ((AssessmentListFragment) viewPagerAdapter.getItem(2)).onResumeFragment();
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

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

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

                        int count = 0;
                        try {
                            count = Integer.parseInt(Objects.requireNonNull(response.body()).getNot_read_count());
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        badge.setNumber(count);
                        try {
                            ShortcutBadger.applyCount(AMHomeActivity.this, count);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(Call<NotificationResponse> call, Throwable t) {
                }
            });
        } 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(AMHomeActivity.this, cnt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public class MainPagerAdapter extends FragmentStatePagerAdapter {

        ArrayList<FragmentItem> fragments;

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

        @NonNull
        @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();
        }
    }

    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("HYPER-M")
                .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;
    }
}