interface HTML5 extends Window {
    plus?: any; // eslint-disable-line
}

export default new (class {
    private h5 = new Promise<HTML5>((resolve) => {
        document.addEventListener('plusready', () => {
            resolve(window);
        })
    })

    constructor() {
        // 监听返回按钮事件
        this.onPlusReady((plus) => {
            let firstBack = true;
            const webview = plus.webview.currentWebview();

            plus.key.addEventListener('backbutton', () => {
                // eslint-disable-next-line
                webview.canBack((e: any) => {
                    // 判断能否继续返回
                    if (e.canBack) {
                        webview.back();
                    } else {
                        // 1秒内连续两次按返回键退出应用
                        if (firstBack) {
                            firstBack = false;
                            plus.nativeUI.toast('再按一次退出应用');
                            setTimeout(() => {
                                firstBack = true;
                            }, 1000);
                        } else {
                            plus.runtime.quit();
                        }
                    }
                })
            })
        })
    }

    // eslint-disable-next-line
    onPlusReady(callback: (plus: any) => void) {
        this.h5.then((res) => {
            callback(res.plus)
        })
    }

    /**
     * 获取状态栏高度
     * @param callback 
     */
    getStatusBarHeight(callback: (statusbarHeight: number) => void) {
        this.onPlusReady((plus) => {
            const height = plus.navigator.getStatusbarHeight();
            callback(height);
        })
    }

    /**
     * 设置状态栏文字颜色
     * @param color dark - 暗色，light - 亮色
     */
    setStatusBarStyle(color: 'dark' | 'light') {
        this.onPlusReady((plus) => {
            plus.navigator.setStatusBarStyle(color);
        })
    }

    /**
     * 隐藏状态栏
     */
    hideStatusBar() {
        this.onPlusReady((plus) => {
            plus.navigator.setFullscreen(true);
        })
    }

    /**
     * 显示状态栏
     */
    showStatusBar() {
        this.onPlusReady((plus) => {
            plus.navigator.setFullscreen(false);
        })
    }

    /**
     * 设置应用全屏
     */
    setFullSreen() {
        this.onPlusReady((plus) => {
            this.hideStatusBar();
            plus.navigator.hideSystemNavigation();
        })
    }

    /**
     * 应用退出全屏
     */
    exitFullSreen() {
        this.onPlusReady((plus) => {
            this.showStatusBar();
            plus.navigator.showSystemNavigation();
        })
    }
})