/*
 * Copyright (C) 2022 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, EventEmitter, Input, Output} from '@angular/core';
import {DocumentAction, PAIADocument, PAIADocumentStatus, PAIADocumentVisualStatus} from '../../../types';
import {LibraryAccountService} from '../../library-account.service';

@Component({
  selector: 'stapps-paia-item',
  templateUrl: './paiaitem.html',
  styleUrls: ['./paiaitem.scss'],
})
export class PAIAItemComponent {
  private _item: PAIADocument;

  renewable: boolean;

  visualStatus?: PAIADocumentVisualStatus;

  constructor(private readonly libraryAccountService: LibraryAccountService) {}

  @Input()
  set item(value: PAIADocument) {
    this._item = value;
    void this.setRenewable();
    this.visualStatus = this.getVisualStatus(Number(this.item.status));
  }

  get item(): PAIADocument {
    return this._item;
  }

  @Input()
  propertiesToShow: (keyof PAIADocument)[];

  @Input()
  listName: string;

  @Output()
  documentAction: EventEmitter<DocumentAction> = new EventEmitter<DocumentAction>();

  async onClick(action: DocumentAction['action']) {
    this.documentAction.emit({doc: this.item, action});
  }

  private async setRenewable() {
    const isActive = await this.libraryAccountService.isActivePatron();
    this.renewable = isActive && Number(this.item.status) === PAIADocumentStatus.Held;
  }

  private getVisualStatus(status: PAIADocumentStatus): PAIADocumentVisualStatus | undefined {
    switch (status) {
      case PAIADocumentStatus.Ordered: {
        return {color: 'warning', status: status, statusText: 'ordered'};
      }
      case PAIADocumentStatus.Provided: {
        return {color: 'success', status: status, statusText: 'ready'};
      }
      default: {
        return undefined;
      }
    }
  }
}
