package com.steps.tmuapp;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;

import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.play.core.appupdate.AppUpdateInfo;
import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.install.InstallState;
import com.google.android.play.core.install.InstallStateUpdatedListener;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.InstallStatus;
import com.google.android.play.core.install.model.UpdateAvailability;
import com.google.firebase.FirebaseApp;
import com.steps.tmuapp.lib.FcmRegistration;
import com.steps.tmuapp.lib.FileChooser;
import com.steps.tmuapp.lib.NetworkUtils;
import com.steps.tmuapp.lib.Permissions;
import com.steps.tmuapp.lib.PreferenceHelper;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import static com.google.android.play.core.install.model.AppUpdateType.IMMEDIATE;
import static com.steps.tmuapp.MyFirebaseMessagingService.FCM_NOTIFICATION_SIGN;
import static com.steps.tmuapp.lib.PreferenceHelper.PREFERENCE_NOTIFICATION_ASKED;

public class MainActivity extends AppCompatActivity {

    public String telUrl = ""; //The tel: phone number URL to dial
    private final static int REQUEST_USER_NAME = 1;
    private final static int REQUEST_SIGNOUT = 2;
    private PreferenceHelper mPreferenceHelper;
    private static final String PREFERENCE_USER_EMAIL = "UN";
    private static final String TAG = MainActivity.class.getSimpleName();
    private WebView mAcademyWebView;
    private MyWebViewClient mAcademyWebViewClient;
    private WebView mFcmWebView;
    private MyWebViewClient mFcmWebViewClient;
    private WebView mEventShowWebView;
    private MyWebViewClient mEventShowWebViewClient;
    private WebView mBulletinWebView;
    private MyWebViewClient mBulletinWebViewClient;
    List<WebView> mWebViewList;
    androidx.appcompat.widget.Toolbar mToolBar;
    private TextView mToolbarTitle;
    private ImageView mLogo;
    private WebView currentWebView;
    private ProgressBar mProgressBar;
    private final int REQUEST_CODE_UPDATE_APP = 1001;
    public static String devicd_id;
    private void switchToWebView(WebView webView) {
        for (WebView item : mWebViewList) {
            if (item == webView) {
                item.setVisibility(View.VISIBLE);
                currentWebView = webView;
            } else {
                item.setVisibility(View.GONE);
            }
        }
    }
    private TemplateApp templateApp;

    private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = item -> {
        int id = item.getItemId();
        if (id == R.id.tab1) {
            LoadBulletinHomePage(true);
            return true;
        } else if (id == R.id.tab2) {
            LoadEventShowHomePage(true);
            return true;
        } else if (id == R.id.tab3) {
            LoadAcademyHomePage(true);
            return true;
        }
        return false;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 让状态栏透明，Toolbar 延伸到状态栏下方
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark, getTheme()));
            // 如果需要状态栏图标为浅色（因为背景是深红色）
            getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            );
        }
        
        // Manually initialize FirebaseApp
        if (FirebaseApp.getApps(this).isEmpty()) {
            FirebaseApp.initializeApp(this.getApplicationContext());
        }
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        mPreferenceHelper = new PreferenceHelper(this);
        if (!(mPreferenceHelper.getConfigString("lang").equals("tw") ||
                mPreferenceHelper.getConfigString("lang").equals("en"))) {
            mPreferenceHelper.setConfig("lang","tw");
        }
        if(!mPreferenceHelper.getConfigString(PREFERENCE_NOTIFICATION_ASKED).equals("YES")){
            requestNotificationPermission();
        }
        templateApp = (TemplateApp) getApplication();
        SaveCooke();

        mProgressBar = findViewById(R.id.progressBar);
        mToolBar = findViewById(R.id.toolbar);
        mToolbarTitle = findViewById(R.id.toolbar_title);
        mLogo = findViewById(R.id.toolbar_logo);
        setSupportActionBar(mToolBar);
        if(getSupportActionBar()!=null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        BottomNavigationView navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        // Academy WebView 主功能
        mAcademyWebView = findViewById(R.id.academy_web_view);
        mAcademyWebViewClient = new MyWebViewClient(this, getSupportActionBar());
        setUpWebViewDefaults(mAcademyWebView, mAcademyWebViewClient);
        // Show WebView 展演公告
        mEventShowWebView = findViewById(R.id.show_web_view);
        mEventShowWebViewClient = new MyWebViewClient(this, getSupportActionBar());
        setUpWebViewDefaults(mEventShowWebView, mEventShowWebViewClient);
        // Bulletin WebView 校園公告
        mBulletinWebView = findViewById(R.id.bulletin_web_view);
        mBulletinWebViewClient = new MyWebViewClient(this, getSupportActionBar());
        setUpWebViewDefaults(mBulletinWebView, mBulletinWebViewClient);
        // Fcm WebView 推播
        mFcmWebView = findViewById(R.id.fcm_web_view);
        mFcmWebViewClient = new MyWebViewClient(this, getSupportActionBar());
        setUpWebViewDefaults(mFcmWebView, mFcmWebViewClient);
        mWebViewList = Arrays.asList(mBulletinWebView, mEventShowWebView, mAcademyWebView, mFcmWebView);
        navigation.setSelectedItemId(R.id.tab3);
        invalidateOptionsMenu();
        prepare_update();
        Bundle extras = getIntent().getExtras();
        if (extras != null ) {
            boolean gotNotifyInBackground = false;
            for (String key : extras.keySet()) {
                Object value = extras.get(key);
                Log.d(TAG, "Extras received at onCreate:  Key: " + key + " Value: " + value);
                if (key.equals("from") && value.equals("581810161777")){
                    LoadFcmHomePage(true);
                    gotNotifyInBackground = true;
                    break;
                }
            }
            if (!gotNotifyInBackground) {
                boolean weakByFcmMessageUserClick = false;
                if(getIntent().getExtras().getString("target")!= null){
                    getIntent().getExtras().getString("target").contains(FCM_NOTIFICATION_SIGN);
                }

                if (weakByFcmMessageUserClick) {
                    LoadFcmHomePage(true);
                } else {
                    new FcmRegistration(this).registerPushServer();
                }
            }
        }else{
            new FcmRegistration(getApplicationContext()).registerPushServer();
        }
        invalidateOptionsMenu();
        devicd_id = getDeviceID();
        templateApp.setDeviceId(devicd_id);
    }

    private void requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
            boolean areNotificationsEnabled = notificationManager.areNotificationsEnabled();
            if (!areNotificationsEnabled) {
                Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                        .putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
                startActivity(intent);
            }
        }
        mPreferenceHelper.setConfig(PREFERENCE_NOTIFICATION_ASKED, "YES");
    }

    private String getDeviceID(){
        String android_id = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
        Log.d(TAG, "android_id=" + android_id);
        return android_id;
    }

    private AppUpdateManager mAppUpdateManager;
    private Task<AppUpdateInfo> appUpdateInfo;
    private static final int RC_APP_UPDATE = 11;

    private void prepare_update() {
        mAppUpdateManager = AppUpdateManagerFactory.create(this);

        // 獲取更新信息
        appUpdateInfo = mAppUpdateManager.getAppUpdateInfo();

        // 註冊 InstallStateUpdatedListener
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(null, new IntentFilter("com.google.android.play.core.listener.b"));
        }
        mAppUpdateManager.registerListener(installStateUpdatedListener);

        // 添加回調處理
        appUpdateInfo.addOnSuccessListener(appUpdateInfo -> {
                    if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
                        if (appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
                            Log.d(TAG, "App update Flexible");
                            requestUpdate(appUpdateInfo, AppUpdateType.FLEXIBLE);
                        } else if (appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                            Log.d(TAG, "App update IMMEDIATE");
                            requestUpdate(appUpdateInfo, AppUpdateType.IMMEDIATE);
                        }
                    }
                }).addOnFailureListener(e -> Log.d(TAG, "Update fail: " + e.getMessage()))
                .addOnCompleteListener(task -> Log.d(TAG, "Update onComplete: "));
    }
    private void requestUpdate(AppUpdateInfo appUpdateInfo, int updateType) {
        try {
            mAppUpdateManager.startUpdateFlowForResult(appUpdateInfo, updateType, MainActivity.this, REQUEST_CODE_UPDATE_APP);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= 21) {
            mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(  appUpdateInfo ->{
                // If the update is downloaded but not installed, notify the user to complete the update.
                if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
                    popupSnackbarForCompleteUpdate();
                } else if (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
                        && appUpdateInfo.isUpdateTypeAllowed(IMMEDIATE)) {
                    try {
                        mAppUpdateManager.startUpdateFlowForResult(appUpdateInfo, IMMEDIATE, this, REQUEST_CODE_UPDATE_APP);
                    } catch (IntentSender.SendIntentException e) {
                        Log.e(TAG, "MainActivity onResume:" + e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * Convenience method to set some generic defaults for a
     * given WebView
     */
    private void setUpWebViewDefaults(WebView webView, MyWebViewClient myWebViewClient) {
        webView.setWebViewClient(myWebViewClient);
        WebSettings settings = webView.getSettings();

        // Enable Javascript
        settings.setJavaScriptEnabled(true);

        // Use WideViewport and Zoom out if there is no viewport defined
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        // Enable pinch to zoom without the zoom buttons
        settings.setBuiltInZoomControls(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setDomStorageEnabled(true);
//        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);//开启DOM缓存，关闭的话H5自身的一些操作是无效的
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setAllowFileAccessFromFileURLs(true);

        // We set the WebViewClient to ensure links are consumed by the WebView rather
        // than passed to a browser if it can
        webView.setWebChromeClient(new MyWebChromeClient(this, mProgressBar));
        webView.addJavascriptInterface(new JavaScriptInterface(this), "AppJavascript");
    }

    private boolean isLoginCheck(){
//        String cookie = CookieManager.getInstance().getCookie(getString(R.string.academy_web_address));
//        return cookie!=null;
        String email = mPreferenceHelper.getConfigString(PreferenceHelper.PREFERENCE_USER_EMAIL);
        return !email.equals("xxxNoEmailxxx") && !email.isEmpty();
    }

    private class JavaScriptInterface {
        private final MainActivity activity;
        private JavaScriptInterface(Activity activiy) {
            this.activity = (MainActivity) activiy;
        }
        @JavascriptInterface
        public void updateTitle(final String title) {
            runOnUiThread(() -> {
                if (title.length()>0) {
                    mToolbarTitle.setText(htmlToString(title));
                    mToolbarTitle.setVisibility(View.VISIBLE);
                    mToolbarTitle.invalidate();
                    mLogo.setVisibility(View.GONE);
                    mLogo.invalidate();
                }else{
                    mToolbarTitle.setText("");
                    mToolbarTitle.setVisibility(View.GONE);
                    mToolbarTitle.invalidate();
                    mLogo.setVisibility(View.VISIBLE);
                    mLogo.invalidate();
                }
            });
        }

        @JavascriptInterface
        public void showAlert(String content) {
            Toast.makeText(activity, content, Toast.LENGTH_SHORT).show();
        }

        //HTML 轉為字串
        private String htmlToString(String sourceString){
            // 定義正則表達式來搜索中文字元的轉義符號
            Pattern compile = Pattern.compile("&#.*?;");
            // 測試用中文字元
            Matcher matcher = compile.matcher(sourceString);
            // 循環搜索 並轉換 替換
            while (matcher.find()) {
                String group = matcher.group();
                // 獲得16進制的碼
                String hexcode = "0" + group.replaceAll("(&\\#|;)", "");
                // 字元串形式的16進制碼轉成int並轉成char 並替換到源串中
                sourceString = sourceString.replaceAll(group, (char) Integer.decode(hexcode).intValue() + "");
            }
            return sourceString;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        // The request code is specified in startActivityForResult(intent, REQUEST_USER_NAME); method.
        if (requestCode == REQUEST_USER_NAME) {
            // GoogleSignIn Callback
            // This request code is set by startActivityForResult(intent, REQUEST_USER_NAME) method.
            if (resultCode == RESULT_OK) {
                String userEmail = "";
                if (data != null) {
                    userEmail = data.getStringExtra("userEmail");
                }
                mPreferenceHelper.setConfig(PREFERENCE_USER_EMAIL, userEmail);
                SaveCooke();
                LoadAcademyHomePage(true);
                LoadFcmHomePage(false);
                invalidateOptionsMenu();
                new FcmRegistration(MainActivity.this).registerPushServer();
            }
        }else if (requestCode == REQUEST_SIGNOUT)
        {
            ClearLoginData();
            invalidateOptionsMenu();
            LoadAcademyHomePage(true);
            LoadFcmHomePage(false);
            new FcmRegistration(MainActivity.this).registerPushServer();
            finish();
        }else if (requestCode == RC_APP_UPDATE) {
            if (resultCode != RESULT_OK) {
                Log.e(TAG, "onActivityResult: app download failed");
            }
        }else {
            if (requestCode == Permissions.CHOOSE_FILE_REQUEST) {
                if (resultCode != RESULT_OK) {
                    FileChooser.filePathCallback.onReceiveValue(null);
                    FileChooser.filePathCallback = null;
                    return;
                }
                // If there is not data, then we have taken a photo
                Uri result;
                if (data == null) {
                    //chooseUploadFile();
//                result = Uri.parse(cameraPhotoPath);
                    result = FileChooser.cameraPhotoUri;
                } else {
                    result = data.getData();
                }

                // The official WebView file chooser API
                // Available since Lollipop - API Level 21 (Android 5.0)
                /*
                 * If the user selected multiple files, they will be stored in ClipData.
                 * But for here, it is a file upload input in WebView.  This is not our case.
                 */
                FileChooser.filePathCallback.onReceiveValue(new Uri[]{result});
                FileChooser.filePathCallback = null;
                FileChooser.cameraPhotoUri = null;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void ClearLoginData(){
        mPreferenceHelper.setConfig(PREFERENCE_USER_EMAIL,"");
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookies(null);
        cookieManager.flush();
    }
    private void SaveCooke(){
        String userEmail = mPreferenceHelper.getConfigString(PREFERENCE_USER_EMAIL);
        //若email不為空表示已經登入成功
        CookieManager cookieManager = CookieManager.getInstance();
        if (!userEmail.equals("")) {
            //使用固定Account做測試用
//            mPreferenceHelper.setConfig(PREFERENCE_USER_EMAIL, "B101103055@tmu.edu.tw");
            String jwtString = getJwtString(userEmail,
                    mPreferenceHelper.getConfigString(PreferenceHelper.PREFERENCE_LANGUAGE));
            cookieManager.removeAllCookies(null);
            String domain_academy = getString(R.string.academy_web_address);
            String userProfileCookieName = getString(R.string.user_profile_cookie_name);
            cookieManager.setCookie(domain_academy, String.format("%s=%s", userProfileCookieName, jwtString));
            //因為fcm會用到使用者的Cookie所以也要存cookie
            String domain_fcm = getString(R.string.fcm_web_address);
            cookieManager.setCookie(domain_fcm, String.format("%s=%s", userProfileCookieName, jwtString));
            cookieManager.flush();
        } else {
            String jwtString = getJwtString("xxxNoEmailxxx",
                    mPreferenceHelper.getConfigString(PreferenceHelper.PREFERENCE_LANGUAGE));
            cookieManager.removeAllCookies(null);
            String domain_academy = getString(R.string.academy_web_address);
            String userProfileCookieName = getString(R.string.user_profile_cookie_name);
            cookieManager.setCookie(domain_academy, String.format("%s=%s", userProfileCookieName, jwtString));
            //因為fcm會用到使用者的Cookie所以也要存cookie
            String domain_fcm = getString(R.string.fcm_web_address);
            cookieManager.setCookie(domain_fcm, String.format("%s=%s", userProfileCookieName, jwtString));
            cookieManager.flush();
//            cookieManager.removeAllCookies(null);
//            cookieManager.flush();
        }
    }
    private void LoadAcademyHomePage(boolean isTakeToForground) {
        NetworkUtils.checkAndRetryNetwork(this);
        if (NetworkUtils.isNetworkAvaliable(this)) {
            String url = getString(R.string.academy_web_address) + "?b="
                    + (new Date().getTime())
                    + "&lang=" + mPreferenceHelper.getConfigString("lang");
            mAcademyWebViewClient.shouldClearHistory = true;
            mAcademyWebView.loadUrl(url);
            mAcademyWebView.clearHistory();
            if (isTakeToForground) switchToWebView(mAcademyWebView);
        }
    }

    private void LoadFcmHomePage(boolean isTakeToForground) {
        NetworkUtils.checkAndRetryNetwork(this);
        if (NetworkUtils.isNetworkAvaliable(this)) {
            String url = getString(R.string.fcm_web_address) + "?b="
                    + (new Date().getTime())
                    + "&lang=" + mPreferenceHelper.getConfigString("lang");
            mFcmWebViewClient.shouldClearHistory = true;
            mFcmWebView.loadUrl(url);
            mFcmWebView.clearHistory();
            if (isTakeToForground) switchToWebView(mFcmWebView);
        }
    }

    private void LoadEventShowHomePage(boolean isTakeToForground) {
        NetworkUtils.checkAndRetryNetwork(this);
        if (NetworkUtils.isNetworkAvaliable(this)) {
            String url = getString(R.string.event_show_web_address) + "?b="
                    + (new Date().getTime())
                    + "&lang=" + mPreferenceHelper.getConfigString("lang");
            mEventShowWebViewClient.shouldClearHistory = true;
            mEventShowWebView.loadUrl(url);
            mEventShowWebView.clearHistory();
            if (isTakeToForground) switchToWebView(mEventShowWebView);
        }
    }

    private void LoadBulletinHomePage(boolean isTakeToForground) {
        NetworkUtils.checkAndRetryNetwork(this);
        if (NetworkUtils.isNetworkAvaliable(this)) {
            String url = getString(R.string.bulletin_web_address) + "?b="
                    + (new Date().getTime())
                    + "&lang=" + mPreferenceHelper.getConfigString("lang");
            mBulletinWebViewClient.shouldClearHistory = true;
            mBulletinWebView.loadUrl(url);
            mBulletinWebView.clearHistory();
            if (isTakeToForground) switchToWebView(mBulletinWebView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "installState destroy");
        mAppUpdateManager.unregisterListener(installStateUpdatedListener);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;

            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.main_menu, menu);
            if (isLoginCheck()) {
                menu.findItem(R.id.menu_item_login).setVisible(false);
                menu.findItem(R.id.menu_item_logout).setVisible(true);
            }else {
                menu.findItem(R.id.menu_item_login).setVisible(true);
                menu.findItem(R.id.menu_item_logout).setVisible(false);
            }
            if (mPreferenceHelper.getConfigString("lang").equals("en")) {
                if (isLoginCheck()) {
                    String userEmail = mPreferenceHelper.getConfigString(PREFERENCE_USER_EMAIL);
                    if (userEmail.indexOf('@') >=0) {
                        String userAccount = userEmail.substring(0, userEmail.indexOf('@'));
                        menu.findItem(R.id.menu_item_logout).setTitle("Logout(" + userAccount + ")");
                    }
                }else{
                    menu.findItem(R.id.menu_item_login).setTitle("Login");
                }
                menu.findItem(R.id.menu_item_home).setTitle("Home");
                menu.findItem(R.id.menu_item_notification).setTitle("Notification");
                menu.findItem(R.id.menu_item_switch_to_en).setVisible(false);
                menu.findItem(R.id.menu_item_switch_to_tw).setVisible(true);
                menu.findItem(R.id.menu_item_app_version).setTitle("Version: "+ version);
            } else {
                if (isLoginCheck()) {
                    String userEmail = mPreferenceHelper.getConfigString(PREFERENCE_USER_EMAIL);
                    if (userEmail.indexOf('@')>0) {
                        String userAccount = userEmail.substring(0, userEmail.indexOf('@'));
                        menu.findItem(R.id.menu_item_logout).setTitle("登出(" + userAccount + ")");
                    }
                }else{
                    menu.findItem(R.id.menu_item_login).setTitle("登入");
                }
                menu.findItem(R.id.menu_item_home).setTitle("首頁");
                menu.findItem(R.id.menu_item_notification).setTitle("檢視推播");
                menu.findItem(R.id.menu_item_switch_to_en).setVisible(true);
                menu.findItem(R.id.menu_item_switch_to_tw).setVisible(false);
                menu.findItem(R.id.menu_item_app_version).setTitle("版本: "+ version);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent signInIntent = new Intent(MainActivity.this, SignInActivity.class);
        int id = item.getItemId();
        if (id == R.id.menu_item_home) { //回首頁
            LoadAcademyHomePage(true);
            invalidateOptionsMenu();
        } else if (id == R.id.menu_item_logout) { //登出
            signInIntent.putExtra(SignInActivity.EXECUTE_SIGNOUT_SILENTLY, true);
            startActivityForResult(signInIntent, REQUEST_SIGNOUT);
        } else if (id == R.id.menu_item_login) { //登入
            startActivityForResult(signInIntent, REQUEST_USER_NAME);
        } else if (id == R.id.menu_item_switch_to_en) { //切換為英文
            mPreferenceHelper.setConfig(PreferenceHelper.PREFERENCE_LANGUAGE, "en");
            SaveCooke();
            LoadAcademyHomePage(true);
            invalidateOptionsMenu();
        } else if (id == R.id.menu_item_notification) { //檢視推播
            LoadFcmHomePage(true);
            return true;
        } else if (id == R.id.menu_item_switch_to_tw) { //切換為中文
            mPreferenceHelper.setConfig(PreferenceHelper.PREFERENCE_LANGUAGE, "tw");
            SaveCooke();
            LoadAcademyHomePage(true);
            invalidateOptionsMenu();
        } else if (id == R.id.menu_item_app_version) { //版號顯示
            // Do nothing
        } else if (id == android.R.id.home) { //回上頁箭頭
            currentWebView.goBack();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * Callback for the result from requesting permissions.
     *
     * @param requestCode  The request code passed in requestPermissions(String[], int).
     * @param permissions  The requested permissions. Never null.
     * @param grantResults The grant results for the corresponding permissions which is either
     *                     PackageManager.PERMISSION_GRANTED or PackageManager.PERMISSION_DENIED.
     *                     Never null.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Map<String, Boolean> permissionMap = new HashMap<>();
        boolean isPermitted;
        if (requestCode == Permissions.REQUEST_PHONE_PERMISSION) {// Maybe permissions are different than PHONE_PERMISSIONS?
            // Sets the default of each PHONE_PERMISSIONS to false.
            for (String permission : Permissions.PHONE_PERMISSIONS) {
                permissionMap.put(permission, false);
            }
            // Sets the permission returned from the user.
            for (int i = 0; i < permissions.length; i++) {
                permissionMap.put(permissions[i],
                        (grantResults[i] == PackageManager.PERMISSION_GRANTED));
            }
            // Collects the result with and (&&).
            isPermitted = true;
            for (String permission : Permissions.PHONE_PERMISSIONS) {
                Boolean perm = permissionMap.get(permission);
                if (perm != null)
                    isPermitted = isPermitted && perm;
            }

            if (isPermitted) {
                Log.d(TAG, "Phone Permission: Answer: Permitted");
                dialPhoneNumber(telUrl);
            } else {
                Log.d(TAG, "Phone Permission: Answer: Denied");
            }
        }
    }
    public String getJwtString(String email,String language) {
        Date expireDate = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(expireDate);
        c.add(Calendar.DATE, 100);
        expireDate = c.getTime();
        return Jwts.builder()
                .setIssuer("tmu-app")
                .setSubject("Tmuapp")
                .setAudience("tmu-app")
                .claim("uname","")
                .claim("tmuid", "")
                .claim("dept","")
                .claim("firdept","")
                .claim("language", language)
                .claim("role", "")
                .claim("email", email)
                .setExpiration(expireDate) //a java.util.Date
                .setIssuedAt(new Date())
                .signWith(Keys.hmacShaKeyFor(getKeyBytes()), SignatureAlgorithm.HS256)
                .compact();
    }

    private byte[] getKeyBytes() {
        String str = getString(R.string.cookiePrivateKey);
        byte[] b = new byte[str.length()];
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) str.charAt(i);
        }
        return b;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && currentWebView.canGoBack()) {
            currentWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private String getLanguage() {
        Locale locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = LocaleList.getDefault().get(0);
        } else locale = Locale.getDefault();

        String language = locale.getLanguage() + "-" + locale.getCountry();
        language = language.substring(0, language.indexOf("-"));
        return language;
    }

    /**
     * Dials the phone number.
     *
     * @param telUrl the tel: phone number URL
     */
    private void dialPhoneNumber(String telUrl) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse(telUrl);
        intent.setData(data);
        startActivity(intent);
    }

    InstallStateUpdatedListener installStateUpdatedListener = new
            InstallStateUpdatedListener() {
                @Override
                public void onStateUpdate(InstallState state) {
                    Log.d(TAG, "installState = " + state.toString());
                    if (state.installStatus() == InstallStatus.DOWNLOADED){
                        //CHECK THIS if AppUpdateType.FLEXIBLE, otherwise you can skip
                        popupSnackbarForCompleteUpdate();
                    } else if (state.installStatus() == InstallStatus.INSTALLED){
                        if (mAppUpdateManager != null){
                            mAppUpdateManager.unregisterListener(installStateUpdatedListener);
                        }
                    } else if (state.installStatus() == InstallStatus.FAILED){
                        Log.i(TAG, "InstallStateUpdatedListener:  " + state.installStatus());
                        //popupSnackbarForFailUpdate();
                    }else {
                        Log.i(TAG, "InstallStateUpdatedListener: state: " + state.installStatus());
                    }
                }
            };

    void popupSnackbarForCompleteUpdate() {
        Snackbar snackbar =
                Snackbar.make(findViewById(android.R.id.content), "An update has just been downloaded.", Snackbar.LENGTH_INDEFINITE);
        snackbar.setAction("Restart", view -> mAppUpdateManager.completeUpdate());
        snackbar.setActionTextColor(getResources().getColor(android.R.color.white));
        snackbar.show();
    }
    void popupSnackbarForFailUpdate() {
        Snackbar snackbar =
                Snackbar.make(findViewById(android.R.id.content), "更新失敗.", Snackbar.LENGTH_INDEFINITE);
        snackbar.setAction("重新安裝", view -> mAppUpdateManager.completeUpdate());
        snackbar.setActionTextColor(getResources().getColor(android.R.color.white));
        snackbar.show();
    }

}
