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

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

  additionalPropertiesToShow: (keyof PAIAFee)[] = [
    'item',
    'date',
    'feetype',
    'feeid',
  ];

  fines: PAIAFee[];

  constructor(private readonly libraryAccountService: LibraryAccountService) {}

  async ionViewWillEnter(): Promise<void> {
    let fees: PAIAFees;
    try {
      fees = await this.libraryAccountService.getFees();
      this.amount = fees.amount;
      this.fines = this.cleanUp(fees.fee);
    } catch {
      // TODO: error handling
    }
  }

  private cleanUp(fines: PAIAFee[]): 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;
  }
}
