/*
 * Copyright (C) 2021 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 {TokenResponse, TokenResponseJson} from '@openid/appauth';
import {nowInSeconds} from '@openid/appauth';

const AUTH_EXPIRY_BUFFER = 10 * 60 * -1; // 10 mins in seconds

export interface PAIATokenResponseJson extends TokenResponseJson {
  patron: string;
}

export class PAIATokenResponse extends TokenResponse {
  patron: string;

  constructor(response: PAIATokenResponseJson) {
    super(response);
    this.patron = response.patron;
  }

  toJson(): PAIATokenResponseJson {
    return {
      access_token: this.accessToken,
      id_token: this.idToken,
      refresh_token: this.refreshToken,
      scope: this.scope,
      token_type: this.tokenType,
      issued_at: this.issuedAt,
      expires_in: this.expiresIn?.toString(),
      patron: this.patron,
    };
  }

  isValid(buffer: number = AUTH_EXPIRY_BUFFER): boolean {
    if (this.expiresIn) {
      const now = nowInSeconds();
      return now < this.issuedAt + this.expiresIn + buffer;
    } else {
      return true;
    }
  }
}
