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

@Injectable({
providedIn: 'root'
})

export class AlertService {
    constructor(private toastController: ToastController, public loadingController: LoadingController, public alertController: AlertController) { }

    async presentToast(message: any) {
        const toast = await this.toastController.create({
            message: message,
            duration: 3000
        });
        toast.present();
    }

    // Show the loader for infinite time
    async showLoader(message: any) {
        this.loadingController.create({
            message: message
        }).then((res) => {
            res.present();
        });
    }
    
    // Hide the loader if already created otherwise return error
    async hideLoader() {
        this.checkAndCloseLoader();

        // if theres a delay run check again
        setTimeout(() => this.checkAndCloseLoader(), 1000);
    }
    
    async checkAndCloseLoader() {
       // Use getTop function to find the loader and dismiss only if loader is present.
       const loader = await this.loadingController.getTop();
       // if loader present then dismiss
        if(loader !== undefined) { 
          await this.loadingController.dismiss();
        }
    }

    async presentAlert(header: any, message: any) {
        const alert = await this.alertController.create({
            header: header,
            message: message,
            buttons: [
                {
                    text: 'Ok',
                    role: 'ok',
                }
            ]
        });
    
        await alert.present();
    
        const { role } = await alert.onDidDismiss();
        return role;
    }

    
  async presentAlertConfirm(header: any, message: any, button1: any, button2: any) {
    const alert = await this.alertController.create({
        header: header,
        message: message,
        buttons: [
            {
                text: button1,
                role: button1,
            },{
                text: button2,
                role: button2
            }
        ]
    });

    await alert.present();

    const { role } = await alert.onDidDismiss();
    return role;
}

   
}