$(document).ready(function () {
    if ($('.main-alert').length) {
        setTimeout(function () {
            $('.main-alert').fadeTo(2000, 500).slideUp(500, function () {
                $(".main-alert").slideUp(500);
            })
        }, 3000);
    }

    let user = localStorage.getItem('user');
    if (user > 0) {
        let socket = new WebSocket(localStorage.getItem('socketAddress'));
        socket.onopen = function () {
            console.log("[WS] Connected. Listen messages for user " + user);
        };

        socket.onmessage = function (event) {
            let received = JSON.parse(event.data);
            if (parseInt(received.data.user_id) === parseInt(user)) {
                console.log(received);
                console.log(`[WS] Received data action: ${received.data.action}. Message: ${received.data.message}`);
                if(received.data.payload.download) {
                   document.location.href = '/storage/export/' + received.data.payload.download;
                }
                setTimeout(function () {
                        if (received.data.payload.error) {
                            $('.alerts').append('<div class="main-alert2 alert alert-danger" role="alert">' + received.data.message + '</div>');
                        } else {
                            $('.alerts').append('<div class="main-alert2 alert alert-success" role="alert">' + received.data.message + '</div>');
                        }
                        setTimeout(function () {
                            $('.main-alert2').fadeTo(2000, 500).slideUp(500, function () {
                                $(".main-alert2").slideUp(500);
                            })
                        }, 3000);
                    }, 1000
                );


            }

        };

        socket.onclose = function (event) {
            if (event.wasClean) {
                console.log(`[WS] Closed clear, code=${event.code} reason=${event.reason}`);
            } else {
                console.log('[WS] Connection lost', event);
            }
        };
        socket.onerror = function (error) {
            console.log(`[error] ${error}`);
        };

    }
});
