import $ from "jquery"
import Timer from "easytimer.js"

import alertify from "alertifyjs";
import "alertifyjs/build/css/alertify.css";

const updateTimeText = (timer) => {
    const timeValues = timer.getTimeValues()

    const hours = String(timeValues.minutes + timeValues.hours * 60 + timeValues.days * 1440).padStart(2, '0')
    const seconds = String(timeValues.seconds).padStart(2, '0')

    $('#timer .timer-values').html(`${hours}:${seconds}`)
}

const assignEventListeners = (timer) => {
    timer.addEventListener(
        'secondsUpdated',
        (event) => {
            updateTimeText(timer)
        }
    )

    timer.addEventListener(
        'targetAchieved',
        (event) => {
            $("#is_counting").prop("checked", false)
            $('#timer .timer-values').html("Konec")
        }
    )

    updateTimeText(timer)
}

$(window).ready(
    () => {
        // --- BEGIN Timer ---

        let timer = new Timer({
            countdown: true,
            startValues: {
                minutes: window.startingTime.minutes,
                seconds: window.startingTime.seconds,
            }
        })

        let timerSocket = null
        let isInitialConnect = true

        const connectToSocket = () => {
            timerSocket = new WebSocket(
                (
                    (window.location.protocol === "https:") ?
                    "wss://" : "ws://"
                )
                + window.location.host
                + "/ws/timer/"
            )

            if (!isInitialConnect) {
                alertify.success("Obnovování spojení.")
            }

            isInitialConnect = false

            timerSocket.onmessage = (event) => {
                console.log("Received timer message:", event.data)

                const data = JSON.parse(event.data)

                if ("status" in data) {
                    if (data["status"] === "playing") {
                        // Reset if we are playing again.
                        const remainingTime = timer.getTimeValues()

                        if (remainingTime.seconds === 0 && remainingTime.minutes === 0) {
                            timer = new Timer({
                                countdown: true,
                                startValues: {
                                    minutes: window.startingTime.minutes,
                                    seconds: window.startingTime.seconds,
                                }
                            })

                            assignEventListeners(timer)
                        }

                        timer.start()
                    } else if (data["status"] === "paused") {
                        timer.pause()
                    }
                } else if ("time" in data) {
                    timer.pause()

                    window.startingTime = {
                        minutes: data["time"]["minutes"],
                        seconds: data["time"]["seconds"]
                    }

                    timer = new Timer({
                        countdown: true,
                        startValues: {
                            minutes: window.startingTime.minutes,
                            seconds: window.startingTime.seconds,
                        }
                    })

                    assignEventListeners(timer)
                }
            }

            timerSocket.onclose = (event) => {
                alertify.error("Ztráta spojení, pokoušíme se o zpětné připojení.")

                setTimeout(connectToSocket, 5000)
            }
        }

        connectToSocket()
        assignEventListeners(timer)

        // --- END Timer ---

        // --- BEGIN Controls ---

        $("#pause_play").on(
            "click",
            (event) => {
                $("#is_counting").click()
            }
        )

        $("#is_counting").on(
            "change",
            (event) => {
                if (event.target.checked) {
                    $("#pause_play > .btn__body").html("⏸︎")

                    timerSocket.send(JSON.stringify({
                        "status": "playing"
                    }))
                } else {
                    $("#pause_play > .btn__body").html("⏵︎")

                    timerSocket.send(JSON.stringify({
                        "status": "paused"
                    }))
                }
            }
        )

        $("#update-time").on(
            "click",
            (event) => {
                let minutes = Number($("#minutes").val())
                let seconds = Number($("#seconds").val())

                timerSocket.send(JSON.stringify({
                    "time": {
                        "minutes": minutes,
                        "seconds": seconds
                    }
                }))

                $("#is_counting").prop("checked", false)
            }
        )

        // --- END Controls ---
    }
)