class Barka extends HTMLElement {
    #odtwarzanie = false;

    constructor() {
        super();
        this.shadow = this.attachShadow({ mode: "open" });
    }

    connectedCallback() {
        const styl = document.createElement("style");
        styl.textContent = `
            :host {
                width: 100vw;
                height: 100vh;
                position: fixed;
                top: 0px;
                left: 0px;
                background: #000000;
                z-index: 999999;
            }
            
            audio {
                width: 100%;
            }
            
            canvas {
                position: fixed;
                left: 0;
                right: 0;
                bottom: 0rem;
                width: 100svw;
                height: 12rem;
                margin: auto;
                /* border: .3rem solid #ffffff; */
            }
        `;
        this.shadow.append(styl)
        this.style.display = "none";
    }

    /**
     * Autozapłon
     */
    async kontroler() {
        let godzina2137 = new Date();
        godzina2137.setHours(21, 37);
        let sekundyDo2137 = (godzina2137.getTime() - Date.now()) / 1000;
        const akceptowalneSpoznienie = 600;


        // console.log("dev");
        // barka.start();
        // return;
        if (sekundyDo2137 >= 0) {
            await new Promise(resolve => setTimeout(resolve, sekundyDo2137 * 1000));
            console.log("już czas.");
            barka.start();
        } else if (sekundyDo2137 + akceptowalneSpoznienie >= 0) {
            console.log("lekko po czasie");
            barka.start();
        } else if (sekundyDo2137 < 0) {
            alert("zaimplementować");
        }
    }

    /**
     * Rozpocznij balange
     */
    async start() {
        if (this.#odtwarzanie) {
            return;
        }
        this.#odtwarzanie = true;

        this.style.display = "none";
        for (const child of this.children) {
            child.remove();
        }

        this.audio = document.createElement("audio");
        this.audio.controls = true;
        this.audio.volume = 0.4;
        {
            const src = document.createElement("source")
            src.src = "/assets/sounds/barka.m4a";
            this.audio.appendChild(src);
        }
        this.audio.addEventListener("playing", ev => {
            if (this.audio.played == 1) {
                this.stop();
            }
        })
        try {
            await this.audio.play();
        } catch (err) {
            console.error("Nie udało się puścić barki: ", err)
            this.#odtwarzanie = false;
            return;
        }
        this.shadow.appendChild(this.audio);
        this.style.display = "block";

        this.canvas = document.createElement("canvas");
        this.shadow.appendChild(this.canvas);
        this.ctx2D = this.canvas.getContext("2d");
        this.ctx2D.imageSmoothingEnabled = false;

        this.ctxAud = new AudioContext();
        this.analyser = this.ctxAud.createAnalyser();
        const src = this.ctxAud.createMediaElementSource(this.audio);
        src.connect(this.analyser);

        // LINIJKA SKRADZIONA Z YOUVIDEO PITER NIE OBRAŻ SIE ALE DOSŁOWNIE TYLKO TO SKOPIOWAŁEM I TYLE NA RESZTE NIE PATRZYŁEM
        this.analyser.connect(this.ctxAud.destination);

        this.analyser.fftSize = 2048;
        this.bufferLength = this.analyser.frequencyBinCount;
        this.dataArray = new Uint8Array(this.bufferLength);

        this.#ucyucy();
    }

    stop() {
        this.style.display = "none";
        this.#odtwarzanie = false;
        this.kontroler();
    }

    async #ucyucy() {
        if (this.#odtwarzanie) {
            requestAnimationFrame(async () => {
                await this.#ucyucy()
            });
        }
        this.analyser.getByteTimeDomainData(this.dataArray);

        this.canvas.width = this.canvas.clientWidth;
        this.canvas.height = this.canvas.clientHeight;
        this.ctx2D.clearRect(0, 0, this.canvas.clientWidth, this.canvas.clientHeight);
        
        this.ctx2D.lineWidth = 5;
        this.ctx2D.strokeStyle = "rgb(203, 166, 247)";
        this.ctx2D.beginPath();
        
        const sliceWidth = this.canvas.clientWidth / this.bufferLength;
        const middle = this.canvas.clientHeight / 2;

        let x = 0;

        let peak = 0;

        for (let i = 0; i < this.bufferLength; i++) {
            const v = (this.dataArray[i] / 128.0 - 1) * (1 - this.audio.volume);
            if (peak < v) {
                peak = v;
            }
            const y = v * 4 * middle + middle;

            if (i == 0) {
                this.ctx2D.moveTo(x, y);
            } else {
                this.ctx2D.lineTo(x, y);
            }
        
            x += sliceWidth;
        }

        // Finish the line
        this.ctx2D.lineTo(this.canvas.clientWidth, this.canvas.clientHeight / 2);
        this.ctx2D.stroke();

        if (this.audio.currentTime > 39) {
            this.canvas.style.backgroundColor = "#1e1e2e";
            this.style.backgroundColor = `rgb(${88 + 255 * peak}, ${137 + 255 * peak}, ${194 + 255 * peak}`;
        } else {
            this.canvas.style.backgroundColor = "";
            this.style.backgroundColor = `rgb(${255 * peak}, ${255 * peak}, ${255 * peak}`;
        }
        this.style.scale = 1 + peak / (peak > 0.1 ? 5 : 10);
    }
}

customElements.define("barka-comp", Barka);

async function start() {
    await new Promise(resolve => setTimeout(resolve, 38000))

    const kreciol = document.createElement("img")
    kreciol.src = "https://media1.tenor.com/m/CzW0P5EOQwoAAAAC/jp2gmd-pope.gif";
    kreciol.style.position = "fixed";
    kreciol.style.right = ".5rem";
    kreciol.style.bottom = ".5rem";
    root.appendChild(kreciol);
}

/** @type Barka */
const barka = document.createElement("barka-comp");
document.body.appendChild(barka);
document.addEventListener("DOMContentLoaded", () => {
    barka.kontroler();
});

window.barka = barka;