/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {Component, ContentChild, EventEmitter, Input, Output, TemplateRef, ViewChild} from '@angular/core';
import {
  ActionSheetController,
  AlertController,
  Config,
  IonModal,
  IonRouterOutlet,
  ModalController,
} from '@ionic/angular/standalone';
import {pendingChangesActionSheet, PendingChangesRole} from './pending-changes-action-sheet';
import {TranslatePipe} from '@ngx-translate/core';

@Component({
  selector: 'stapps-edit-modal',
  templateUrl: 'edit-modal.html',
})
export class EditModalComponent {
  @ContentChild(TemplateRef) content: TemplateRef<unknown>;

  @ViewChild('modal') modal: IonModal;

  @Input() pendingChanges = false;

  @Output() save = new EventEmitter();

  constructor(
    readonly modalController: ModalController,
    readonly routerOutlet: IonRouterOutlet,
    readonly alertController: AlertController,
    readonly actionSheetController: ActionSheetController,
    readonly translatePipe: TranslatePipe,
    readonly config: Config,
  ) {}

  present() {
    this.modal.present();
    this.pendingChanges = false;
  }

  dismiss(skipChanges = false) {
    this.pendingChanges = skipChanges ? false : this.pendingChanges;
    setTimeout(() => this.modal.dismiss());
  }

  canDismissModal = async () => {
    const alert =
      this.config.get('mode') === 'ios'
        ? await this.actionSheetController.create(pendingChangesActionSheet(this.translatePipe))
        : await this.alertController.create(pendingChangesActionSheet(this.translatePipe, false));
    alert.present().then();

    const {role} = await alert.onWillDismiss();
    if (role === PendingChangesRole.SAVE) {
      this.save.emit();
    }

    return role !== 'backdrop' && role !== PendingChangesRole.CANCEL;
  };
}
