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

@Injectable({
  providedIn: 'root'
})
export class AlertService {
  isLoading = false;

  private readonly TOAST_DURATION = 3000;
  private readonly TOAST_POSITION = 'top';
  private readonly SUCCESS_TOAST_CLASS = 'success-toast';
  private readonly ERROR_TOAST_CLASS = 'error-toast';

  constructor(
    private toastCtrl: ToastController,
    private loadingCtrl: LoadingController,
  ) { }

  async showLoader() {
    this.isLoading = true;
    const loading = await this.loadingCtrl.create({ duration: 7000 });
    await loading.present();
    if (!this.isLoading) {
      await loading.dismiss();
    }
  }

  async hideLoader() {
    this.isLoading = false;
    await this.loadingCtrl.dismiss();
  }

  async showToaster(text: string) {
    if (text) {
      const toast = await this.toastCtrl.create({
        message: text,
        duration: this.TOAST_DURATION,
        position: this.TOAST_POSITION,
        cssClass: this.SUCCESS_TOAST_CLASS,
      });
      await toast.present();
    }
  }

  async showToasterError(text: string) {
    if (text) {
      const toast = await this.toastCtrl.create({
        message: text,
        duration: this.TOAST_DURATION,
        position: this.TOAST_POSITION,
        cssClass: this.ERROR_TOAST_CLASS,
      });
      await toast.present();
    }
  }

  async showSpinner() {
    this.isLoading = true;
    const loading = await this.loadingCtrl.create();
    await loading.present();
    if (!this.isLoading) {
      await loading.dismiss();
    }
  }
}
