import {Component} from '@angular/core';
import {LibraryAccountService} from '../library-account.service';
import {PAIAFee} from '../../types';

@Component({
  selector: 'app-fines',
  templateUrl: './fines-page.html',
  styleUrls: ['./fines-page.scss'],
})
export class FinesPageComponent {
  amount?: string;

  fines: PAIAFee[];

  constructor(private readonly libraryAccountService: LibraryAccountService) {}

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

  private async cleanUp(fines: PAIAFee[]): Promise<PAIAFee[]> {
    for (const fine of fines) {
      for (const property in fine) {
        // remove properties with "null" included
        if (fine[<keyof PAIAFee>property]?.includes('null')) {
          delete fine.item;
        }
      }
    }
    return fines;
  }

  async fetchItems() {
    try {
      const fees = await this.libraryAccountService.getFees();
      if (fees) {
        this.amount = fees.amount;
        this.fines = await this.cleanUp(fees.fee);
      }
    } catch {
      await this.libraryAccountService.handleError();
    }
  }
}
