/*
 * Copyright (C) Sapphirecode - All Rights Reserved
 * This file is part of Auth-Server-Helper which is released under MIT.
 * See file 'LICENSE' for full license details.
 * Created by Timo Hocker <timo@scode.ovh>, December 2020
 */

interface Signature {
  hash: string;
  iat: number;
}

class Blacklist {
  private _signatures: Signature[];

  public constructor () {
    this._signatures = [];
  }

  public clear (before: number = Number.POSITIVE_INFINITY): void {
    for (let i = this._signatures.length - 1; i >= 0; i--) {
      if (this._signatures[i].iat < before)
        this._signatures.splice (i, 1);
    }
  }

  public add_signature (hash: string): void {
    this._signatures.push ({ iat: Date.now (), hash });
  }

  public remove_signature (hash: string): void {
    for (let i = this._signatures.length - 1; i >= 0; i--) {
      if (this._signatures[i].hash === hash)
        this._signatures.splice (i, 1);
    }
  }

  public is_valid (hash: string): boolean {
    for (const sig of this._signatures) {
      if (sig.hash === hash)
        return false;
    }

    return true;
  }

  public export_blacklist (): Signature[] {
    return this._signatures;
  }

  public import_blacklist (data: Signature[]): void {
    this._signatures.push (...data);
  }
}

const bl = (new Blacklist);

export { Blacklist };
export default bl;