/* eslint-disable @typescript-eslint/ban-ts-comment */
import { expect, fixture, waitUntil } from '@open-wc/testing';
import { html } from 'lit';
import sinon from 'sinon';

import type { PlayerEmbed } from '../index.js';
import type { VideoMap } from '@vouchfor/media-player-legacy';

import { data } from './data.js';

// Can't use typescript aliases with esbuild file transforms apparently
// No idea what a good way to actually build before testing is, the examples give nothing
// https://modern-web.dev/guides/test-runner/typescript/
import '../../../test/lib/embeds-legacy.js';

function getVideo(videos: VideoMap) {
  return Object.values(videos)[0];
}

function playerLoaded(player: PlayerEmbed) {
  return waitUntil(
    () => {
      return player.mediaPlayer?.initialised;
    },
    'Player has not loaded video',
    { timeout: 20000 }
  );
}

describe.skip('Embeds', () => {
  it('Sends correct tracking events', async () => {
    const player = await fixture<PlayerEmbed>(
      html`<vouch-embed-legacy-player env="dev" .data=${data} aspectratio=${1}></vouch-embed-legacy-player>`
    );
    // @ts-ignore - accessing private property
    const sendTrackingSpy = sinon.spy(player._trackingController, '_sendTrackingEvent');
    // @ts-ignore - accessing private property
    const createTrackingSpy = sinon.spy(player._trackingController, '_createTrackingEvent');

    await playerLoaded(player);
    // Have to mute the player because we can't programmatically play videos with sound
    player.muted = true;
    player.play();
    expect(player.paused).eq(false);
    await waitUntil(
      () => {
        // Video plays for 3 seconds
        return (getVideo(player.mediaPlayer!.videos)?.node?.currentTime ?? 0) > 3;
      },
      'Video did not play for 3 seconds',
      { timeout: 20000 }
    );
    expect(getVideo(player.mediaPlayer!.videos)?.node?.paused).eq(false);
    player.pause();
    expect(getVideo(player.mediaPlayer!.videos)?.node?.paused).eq(true);
    expect(sendTrackingSpy.callCount).to.be.eq(0);
    // Destroy node because events are sent when node is removed from the document
    player.remove();
    await waitUntil(
      () => {
        return createTrackingSpy.args[2];
      },
      'Cleanup event has not fired',
      { timeout: 5000 }
    );
    expect(sendTrackingSpy.callCount).to.be.eq(1);
    expect(createTrackingSpy.args[0]).to.eql([
      'VIDEO_PLAYED',
      {
        streamStart: 0
      }
    ]);
    expect(createTrackingSpy.args[1]).to.eql([
      'VOUCH_RESPONSE_VIEWED',
      {
        answerId: '5c66bb3a-ed68-41a0-a601-a49865104418'
      }
    ]);
    expect(createTrackingSpy.args[2][0]).to.eq('VIDEO_STREAMED');
    // Remove streamStart and streamEnd as these are non-deterministic
    expect({ ...createTrackingSpy.args[2][1], streamStart: undefined, streamEnd: undefined }).to.eql({
      answerId: '5c66bb3a-ed68-41a0-a601-a49865104418',
      streamStart: undefined,
      streamEnd: undefined
    });
  });
});
