import MediaPlayer from "../MediaPlayer";

class AutoPause {
    private threshold: number;
    player: MediaPlayer;

    constructor() {
        this.threshold = 0.25;
        this.handleIntersection = this.handleIntersection.bind(this);
        this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
    }
    run(player) {
        this.player = player;
        // const observer = new IntersectionObserver(handler, config)
        const observer = new IntersectionObserver(this.handleIntersection, {
            // threshold: umbral define que porciento del elemento tiene que tener interseccion
            threshold: this.threshold
        })
        observer.observe(player.media);

        document.addEventListener("visibilitychange", this.handleVisibilityChange);
    }

    /**
     * Cuando intersectionObserver llame a handlerIntersection le va a pasar una lista de entries
     * los entries son todos los objetos que estamos observando 
     * */ 
    private handleIntersection(entries: IntersectionObserverEntry[]) {
        const entry = entries[0];
        const isVisible = entry.intersectionRatio >= this.threshold;

        if (isVisible) {
            this.player.play();
        } else {
            this.player.pause();
        }

        // console.log(entry);
    }

    private handleVisibilityChange() {
        const isVisible = document.visibilityState === "visible";

        if (isVisible) {
            this.player.play();
        } else {
            this.player.pause();
        }
    }
}

export default AutoPause;