/*
 * 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} from '@angular/core';
import {DocumentAction, PAIADocument, PAIADocumentStatus} from '../../types';
import {LibraryAccountService} from '../library-account.service';

@Component({
  selector: 'app-checked-out',
  templateUrl: './checked-out-page.html',
  styleUrls: ['./checked-out-page.scss'],
})
export class CheckedOutPageComponent {
  checkedOutItems?: PAIADocument[];

  constructor(private readonly libraryAccountService: LibraryAccountService) {}

  async ionViewWillEnter(): Promise<void> {
    await this.fetchItems();
  }

  async onDocumentAction(documentAction: DocumentAction) {
    const answer = await this.libraryAccountService.handleDocumentAction(documentAction);

    if (answer) await this.fetchItems();
  }

  async fetchItems() {
    try {
      // Prepare patron (status) for the items
      await this.libraryAccountService.getPatron();
      this.checkedOutItems = undefined;
      this.checkedOutItems = await this.libraryAccountService.getFilteredItems([PAIADocumentStatus.Held]);
    } catch {
      await this.libraryAccountService.handleError();
      this.checkedOutItems = [];
    }
  }
}
