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

import { MultiReporter, Reporter, SpadeReporter } from 'tachyon-spade-reporter';

describe('MultiReporter', () => {
  const message = 'ohai';

  class DummyReporter implements Reporter {
    public messages: any[] = [];
    public reportEvent(event: any): void {
      this.messages.push(event);
    }
  }

  it('reports events to a reporter', () => {
    const reporter = new DummyReporter();
    const subject = new MultiReporter([reporter]);
    subject.reportEvent(message);
    expect(reporter.messages).toEqual([message]);
  });

  it('reports events to multiple reporters', () => {
    const reporters = [new DummyReporter(), new DummyReporter()];
    const subject = new MultiReporter(reporters);
    subject.reportEvent(message);
    expect(reporters.map(r => r.messages)).toEqual([[message], [message]]);
  });

  it('does not fail when there are no reporters', () => {
    const subject = new MultiReporter([]);
    expect(() => {
      subject.reportEvent(message);
    }).not.toThrow();
  });

  describe('SpadeReporter', () => {
    const SPADE_URI = 'https://spade.trowel.shovel.hoe.net';
    const PAYLOAD = { iam: 'data' };
    const BASE_64_PAYLOAD = Base64.stringify(
      Utf8.parse(JSON.stringify([PAYLOAD])),
    );

    it('calls fetch with the right data', () => {
      const mock = jest.fn();
      const subject = new SpadeReporter(SPADE_URI, mock);
      subject.reportEvent(PAYLOAD);
      expect(mock).toHaveBeenCalledWith(SPADE_URI, {
        body: `data=${BASE_64_PAYLOAD}`,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        method: 'POST',
        mode: 'no-cors',
      });
    });
  });
});
