import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
import {beforeMapTest, createMap, getMockDispatcher, waitForEvent} from '../util/test/util.ts';
import {extend} from '../util/util.ts';
import {VideoSource} from './video_source.ts';
import {Tile} from '../tile/tile.ts';
import {OverscaledTileID} from '../tile/tile_id.ts';

import type {Coordinates} from './image_source.ts';
import type {Map} from '../ui/map.ts';

let map: Map;

function createSource(options) {
    const c = options?.video || window.document.createElement('video');

    options = extend({coordinates: [[0, 0], [1, 0], [1, 1], [0, 1]]}, options);

    const source = new VideoSource('id', options, getMockDispatcher(), options.eventedParent);

    source.video = c;
    source.map = map;
    return source;
}

describe('VideoSource', () => {
    let source: VideoSource;

    beforeEach(async () => {
        beforeMapTest();
        map = createMap();
        await map.once('style.load');
        // Attribution File:Volcano Lava Sample.webm: U.S. Geological Survey (USGS), Public domain, via Wikimedia Commons
        source = createSource({
            type: 'video',
            urls: ['cropped.mp4', 'https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm'],
            coordinates: [
                [-76.54, 39.18],
                [-76.52, 39.18],
                [-76.52, 39.17],
                [-76.54, 39.17]
            ]
        });
    });

    afterEach(() => {
        map.remove();
    });

    test('constructor', () => {
        expect(source.minzoom).toBe(0);
        expect(source.maxzoom).toBe(22);
        expect(source.tileSize).toBe(512);
    });

    test('sets coordinates', () => {
        const newCoordinates = [[0, 0], [-1, 0], [-1, -1], [0, -1]] as Coordinates;
        source.setCoordinates(newCoordinates);
        const serialized = source.serialize();

        expect(serialized.coordinates).toEqual(newCoordinates);

    });

    //test video retrieval by first supplying the video element directly
    test('gets video', () => {
        const el = window.document.createElement('video');
        // Attribution File:Volcano Lava Sample.webm: U.S. Geological Survey (USGS), Public domain, via Wikimedia Commons
        const source = createSource({
            type: 'video',
            video: el,
            urls: ['cropped.mp4', 'https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm'],
            coordinates: [
                [-76.54, 39.18],
                [-76.52, 39.18],
                [-76.52, 39.17],
                [-76.54, 39.17]
            ]
        });

        expect(source.getVideo()).toBe(el);
    });

    test('fires idle event on prepare call when there is at least one not loaded tile', async () => {
        const video = window.document.createElement('video');
        Object.defineProperty(video, 'readyState', {value: HTMLMediaElement.HAVE_CURRENT_DATA});
        const source = createSource({
            type: 'video',
            urls: [],
            video,
            coordinates: [
                [-76.54, 39.18],
                [-76.52, 39.18],
                [-76.52, 39.17],
                [-76.54, 39.17]
            ]
        });
        const tile = new Tile(new OverscaledTileID(1, 0, 1, 0, 0), 512);
        const dataEvent = waitForEvent(source, 'data', (e) => e.dataType === 'source' && e.sourceDataType === 'idle');
        source.onAdd(map);

        source.tiles[String(tile.tileID.wrap)] = tile;
        source.prepare();
        await dataEvent;
        expect(tile.state).toBe('loaded');
    });

    test('onRemove removes playing listener, pauses video and deletes the texture', () => {
        const video = window.document.createElement('video');
        const removeListenerSpy = vi.spyOn(video, 'removeEventListener');
        const pauseSpy = vi.spyOn(video, 'pause').mockImplementation(() => {});

        const source = createSource({
            type: 'video',
            urls: [],
            coordinates: [[-76.54, 39.18], [-76.52, 39.18], [-76.52, 39.17], [-76.54, 39.17]]
        });
        source.video = video;

        const texture = {destroy: vi.fn()} as any;
        source.texture = texture;

        source.onRemove();

        expect(removeListenerSpy).toHaveBeenCalledWith('playing', expect.any(Function));
        expect(pauseSpy).toHaveBeenCalled();
        expect(texture.destroy).toHaveBeenCalledTimes(1);
        expect(source.texture).toBeNull();
    });
});
