import {Request} from '@prodress/pdr2com';

export class ProdressRequest extends Request {
  public constructor(db: string, handler: string, action: string) {
    super(
      {
        interneProtokollVersion: 1,
        benutzer: '',
        passwort: '',
        programm: handler,
        datenbank: db,
        typ: action,
        transaktionsId: 0,
        protokoll: 0,
        fehlerCode: 0,
        fehlerIsPermanent: 0,
        fehlerText: '',
      },
      Buffer.alloc(0),
      {
        rechenzeit: 0,
        verwendeUtf8: true,
        maximalePaketgröße: 0,
      },
    );
  }

  /**
   * writes entries based on the provided requestTupelList into the request
   * @param requestBody
   */
  public writeEntries(requestBody: Pdr2_RequestBody): void {
    // write additionalInformation
    for (const tupel of requestBody.additionalInformation) {
      this.writeEntry(tupel);
    }

    // write amount of argument entries
    this.writeEntry(['integer', requestBody.arguments.length]);

    // write arguments
    for (const args of requestBody.arguments) {
      for (const tupel of args) {
        this.writeEntry(tupel);
      }
    }
  }

  /**
   * writes an entry based on the provided requestTupel into the request
   * @param requestTupel
   */
  public writeEntry(requestTupel: Pdr2_RequestTupel): void {
    const [type, value] = requestTupel;
    switch (type) {
      case 'string':
        this.schreibeText(value);
        break;
      case 'integer':
        this.schreibeGanzzahl(value);
        break;
      case 'float':
        this.schreibeDezimalzahl(value);
        break;
      case 'date':
        this.schreibeDatum(value);
        break;
      case 'date_time':
        this.schreibeDatumMitZeit(value);
        break;
    }
  }
}
