import * as Base64 from 'crypto-js/enc-base64';
import * as Utf8 from 'crypto-js/enc-utf8';

import { logger } from 'tachyon-logger';
import { Reporter } from 'tachyon-spade-reporter/reporter';

export class SpadeReporter implements Reporter {
  constructor(
    private spadeURI: string,
    private fetchImplementation: typeof fetch,
  ) {
    if (!this.fetchImplementation && typeof window !== 'undefined') {
      this.fetchImplementation = window.fetch.bind(window);
    }
  }

  public reportEvent(event: any): void {
    if (!this.fetchImplementation) {
      logger.error(
        'Attempted to report an event but no fetch implementation available.',
      );
      return;
    }

    const data = Base64.stringify(Utf8.parse(JSON.stringify([event])));

    this.fetchImplementation(this.spadeURI, {
      body: `data=${data}`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      method: 'POST',
      mode: 'no-cors',
    });
  }
}
