import {Injectable} from '@angular/core';
import {LoadingController} from '@ionic/angular';

@Injectable()
export class Loading {
    constructor(public loadingController: LoadingController) {
    }

    loading: any;
    loadingIsOpen: any;
    countdown = 0;
    interval: any;
    async presentLoading(time, showMessage) {
        if (this.loadingIsOpen) {
            clearInterval(this.interval);
        } else {
            console.log('loading is open');
            this.loadingIsOpen = true;
            this.countdown = time;
            this.loading = await this.loadingController.create({
                mode: 'ios',
                spinner: 'circles',
                message: showMessage ? '通信中，还剩 ' + time + ' 秒' : '',
                cssClass: 'main-color',
                duration: time * 1000
            });
            this.loading.present();
            this.interval = window.setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                    this.loading.message = showMessage ? '通信中，还剩 ' + this.countdown + ' 秒' : '';
                } else {
                    this.loading.message = '';
                }
            }, 1000)

            const { role, data } = await this.loading.onDidDismiss();

            console.log('Loading dismissed!');
        }
    }

    async closeLoading() {
        if (this.loading !== undefined || this.loading !== null) {
            console.log('loading is close');
            this.loading.dismiss();
            this.loading.onDidDismiss();
            this.loadingIsOpen = false;
            clearInterval(this.interval);
        }
    }
}
