import {Injectable} from '@angular/core';
// import {ConfigProvider} from '../../config/config.provider';
import {PAIAAuthService} from '../../auth/paia/paia-auth.service';
import {JQueryRequestor, Requestor} from '@openid/appauth';
import {SCFeatureConfigurationExtern, SCMap} from '@openstapps/core';
import {PAIADocumentStatus, PAIAFees, PAIAItems, PAIAPatron} from '../types';
import {HebisDataProvider} from '../../hebis/hebis-data.provider';

@Injectable({
  providedIn: 'root',
})
export class LibraryAccountService {
  // TODO: must come from backend (not that stable)
  private _config: SCMap<SCFeatureConfigurationExtern> = {
    profile: {
      url: 'https://hds.hebis.de:8443/core/{patron}',
    },
    items: {
      url: 'https://hds.hebis.de:8443/core/{patron}/items',
    },
    fees: {
      url: 'https://hds.hebis.de:8443/core/{patron}/fees',
    },
  };

  constructor(
    protected requestor: Requestor = new JQueryRequestor(),
    private readonly paiaAuth: PAIAAuthService,
    private readonly hebisDataProvider: HebisDataProvider,
  ) {}

  get config() {
    return this._config;
  }

  async getProfile() {
    return this.performRequest<PAIAPatron>(this.config.profile.url);
  }

  async getItems() {
    return this.performRequest<PAIAItems>(this.config.items.url);
  }

  async getFees() {
    return this.performRequest<PAIAFees>(this.config.fees.url);
  }

  private async performRequest<T>(urlTemplate: string): Promise<T> {
    const token = await this.paiaAuth.getValidToken();
    const url = urlTemplate.replace('{patron}', token.patron);
    const settings: JQueryAjaxSettings = {
      url: url,
      dataType: 'json',
      method: 'GET',
      headers: {
        'Authorization': `Bearer: ${token.accessToken}`,
        'Content-Type': 'application/json',
      },
    };

    return this.requestor.xhr(settings);
  }

  getRawId(input: string) {
    return input.split(':').pop();
  }

  async getHoldsAndReservations() {
    return (await this.getItems()).doc.filter(document => {
      return [
        PAIADocumentStatus.Reserved,
        PAIADocumentStatus.Ordered,
        PAIADocumentStatus.Provided,
      ].includes(Number(document.status));
    });
  }

  async getCheckedOutItems() {
    return (await this.getItems()).doc.filter(document => {
      // return [PAIADocumentStatus.Held].includes(Number(document.status));
      // TODO: Put back the line above (demo purposes)
      return [PAIADocumentStatus.Rejected].includes(Number(document.status));
    });
  }

  async getDocumentFromHDS(edition: string) {
    if (typeof edition === 'undefined') {
      return;
    }
    const response = await this.hebisDataProvider.hebisSearch(
      {
        query: this.getRawId(edition) as string,
        page: 0,
      },
      {addPrefix: true},
    );

    return response.data[0];
  }
}
