import expect from 'expect';
import { spy } from 'sinon';

import {
  Tracker,
  SpadeEvent,
  getReferrerHost,
  getReferrerDomain,
  getDeviceOrientation,
} from 'mweb/common/tracking/tracker';
import { Reporter } from 'tachyon-spade-reporter';

describe('Tracker', () => {
  class TestReporter implements Reporter {
    constructor(private logSpy: Function) {}

    reportEvent(event: any): void {
      this.logSpy(event);
    }
  }

  it('converts values to downcase when possible', () => {
    const logSpy = spy();
    const tracker = new Tracker(
      new TestReporter(logSpy),
      'appVersion',
      'deviceID',
      'sessionID',
    );

    tracker.trackEvent(({
      event: 'event',
      properties: { number: 2, empty: undefined, string: 'STRING' },
    } as any) as SpadeEvent);

    const callArgsProperties = logSpy.getCall(0).args[0].properties;
    expect(callArgsProperties.number).toEqual(2);
    expect(callArgsProperties.empty).toEqual(undefined);
    expect(callArgsProperties.string).toEqual('string');
    expect(callArgsProperties.app_session_id).toEqual('sessionID');
  });
});

describe('tracker referrer parsing', () => {
  it('gets referrer host', () => {
    expect(getReferrerHost('https://www.reddit.com/r/overwatch')).toEqual(
      'www.reddit.com',
    );
  });

  it('gets referrer domain', () => {
    expect(getReferrerDomain('https://www.reddit.com/r/overwatch')).toEqual(
      'reddit.com',
    );
  });

  it('does not error when referrer is not set', () => {
    expect(getReferrerHost('not a url')).toEqual(undefined);
    expect(getReferrerDomain('not a url')).toEqual(undefined);
  });
});

describe('getDeviceOrientation', () => {
  describe('via window.screen.orientation', () => {
    interface OrientationTestCase {
      type: ScreenOrientationType;
      expected: 'landscape' | 'portrait';
    }
    const testCases: OrientationTestCase[] = [
      { type: 'landscape-primary', expected: 'landscape' },
      { type: 'landscape-secondary', expected: 'landscape' },
      { type: 'portrait-primary', expected: 'portrait' },
      { type: 'portrait-secondary', expected: 'portrait' },
    ];

    testCases.forEach(({ type, expected }) => {
      it(`returns ${expected} for ${type}`, () => {
        window.screen.orientation = { type };
        expect(getDeviceOrientation()).toEqual(expected);
      });
    });

    after(() => {
      window.screen.orientation = undefined;
    });
  });

  describe('via window.orientation', () => {
    const testCases = [
      { orientation: 0, expected: 'portrait' },
      { orientation: 180, expected: 'portrait' },
      { orientation: 90, expected: 'landscape' },
      { orientation: -90, expected: 'landscape' },
    ];

    testCases.forEach(({ orientation, expected }) => {
      it(`returns ${expected} for ${orientation}`, () => {
        window.orientation = orientation;
        expect(getDeviceOrientation()).toEqual(expected);
      });
    });
  });
});
