import {Injectable} from '@angular/core';
import {ActionSheetController, AlertController, MenuController, ModalController, NavController, PopoverController} from '@ionic/angular';

@Injectable()
export class BackService {
  tabsCanGoBack = false;
  tabsParentCanGoBack = false;
  constructor(public nav: NavController,
              public alertCtrl: AlertController,
              public modalCtrl: ModalController,
              public menuCtrl: MenuController,
              public actionSheetCtrl: ActionSheetController,
              public popoverCtrl: PopoverController) {}

  async androidBackButtonHandle(next) {
    try {
      const alert = await this.alertCtrl.getTop();
      if (alert) {
        alert.dismiss();
        return;
      }
      const action = await this.actionSheetCtrl.getTop();
      if (action) {
        action.dismiss();
        return;
      }
      const popover = await this.popoverCtrl.getTop();
      if (popover) {
        popover.dismiss();
        return;
      }
      const modal = await this.modalCtrl.getTop();
      if (modal) {
        modal.dismiss();
        return;
      }
      const isOpen = await this.menuCtrl.isOpen();
      if (isOpen) {
        this.menuCtrl.close();
        return;
      }
      if (!this.tabsCanGoBack && !this.tabsParentCanGoBack) {
        // this.native.appMinimize();
        this.nav.navigateRoot('/' + next);
        return;
      }
    } catch (error) {
    }
  }
}
