import { sound } from '@pixi/sound';
import Locator from '../Locator';

import type { PlayOptions } from '@pixi/sound';
import type { Service } from '../types';

/**
 * Logging audio service used in development environments.
 * It mirrors the service API but outputs actions to the console.
 */
export default class LogAudio implements Service
{
    public name = 'LogAudio';
    public readonly serviceType = 'audio';

    public mute = false;
    public status: 'sound_on' | 'sound_off' = 'sound_on';

    private readonly handleVisibilityChange = (): void =>
    {
        if (this.mute)
        {
            return;
        }

        if (document.visibilityState === 'visible')
        {
            sound.unmuteAll?.();
        }
        else
        {
            sound.muteAll();
        }
    };

    constructor()
    {
        document.addEventListener('visibilitychange', this.handleVisibilityChange);
    }

    public play(name: string, _options?: PlayOptions): void
    {
        if (!name)
        {
            return;
        }

        // eslint-disable-next-line no-console
        console.log(`LogAudio: play ${name}`);
    }

    public stop(name?: string): void
    {
        if (!name)
        {
            return;
        }

        // eslint-disable-next-line no-console
        console.log(`LogAudio: stop ${name}`);
    }

    public find(soundName: string)
    {
        return sound.find(soundName);
    }

    public volume(alias: string, value?: number): number
    {
        return sound.volume(alias, value);
    }

    public get volumeAll(): number
    {
        return 1;
    }

    public set volumeAll(_value: number)
    {
        // noop
    }

    public toggleMute(): void
    {
        this.mute = !this.mute;

        if (this.mute)
        {
            // eslint-disable-next-line no-console
            console.log('LogAudio: mute');
            Locator.events.emit('audio/status/sound_off');
        }
        else
        {
            // eslint-disable-next-line no-console
            console.log('LogAudio: unmute');
            Locator.events.emit('audio/status/sound_on');
        }
    }

    public dispose(): void
    {
        document.removeEventListener('visibilitychange', this.handleVisibilityChange);
    }
}
