import {Component, AfterViewInit} from '@angular/core';

import {Platform} from '@ionic/angular';
import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';
import {Router, NavigationEnd} from '@angular/router';
import { AppMinimize } from '@ionic-native/app-minimize/ngx';
declare var screen: any;

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent implements AfterViewInit {
    constructor(
        private platform: Platform,
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        private appMinimize: AppMinimize,
        private router: Router
    ) {
        this.initializeApp();
    }

    private backBtnPressed;
    private url;
    private flag = 0;

    initializeApp() {
        this.platform.ready().then(() => {
            this.flag++;
            this.registerBackButtonAction(); // 注册返回按键事件
            this.platform.resume.subscribe(); // 弹出框
            this.initRouterListen();
            screen.orientation.lock('portrait');
            if (this.flag === 2) {
                this.statusBar.styleLightContent();
                this.statusBar.backgroundColorByHexString('#000000');
                this.statusBar.show();
                this.statusBar.overlaysWebView(false);
                this.splashScreen.hide();
            }
        });
    }

    ngAfterViewInit(): void {
        this.flag++;
        if (this.flag === 2) {
            this.statusBar.styleLightContent();
            this.statusBar.backgroundColorByHexString('#000000');
            this.statusBar.show();
            this.statusBar.overlaysWebView(false);
            this.splashScreen.hide();
        }
    }

    initRouterListen() {
        this.router.events.subscribe(event => { // 需要放到最后一个执行
            if (event instanceof NavigationEnd) {
                this.url = window.location.pathname;
            }
        });
    }

    registerBackButtonAction() {
        this.platform.backButton.subscribe(() => {
            if (this.url === '/home' || this.url === '/login') {
                if (this.backBtnPressed) {
                    this.appMinimize.minimize();
                    this.backBtnPressed = false;
                    window.history.pushState('forward', null, this.url);
                    return;
                } else {
                    this.backBtnPressed = true;
                    setTimeout(() => this.backBtnPressed = false, 2000);
                    return;
                }
            } else {
                this.backBtnPressed = true;
                setTimeout(() => this.backBtnPressed = false, 2000);
                return;
            }
        });
    }
}
