// Copyright 1999-2025. WebPros International GmbH. All rights reserved.

"use strict";

document.addEventListener('DOMContentLoaded', function () {
    var steps = [
        'initialize',
        'clone'
    ];

    var updateStep = function (step, progress, message) {
        var status = step.getElementsByTagName('span')[0];
        var messageElement = document.getElementById('message');

        if (progress < 100) {
            status.innerText = progress + '%';
        } else {
            status.innerText = 'DONE';
            status.style.color = '#629a1e';
        }

        if (message) {
            messageElement.style.display = '';
            messageElement.innerText = message;
        } else {
            messageElement.style.display = 'none';
        }
    };

    var allDone = function (timer) {
        document.getElementById('done').style.display = '';
        clearInterval(timer);
        steps.forEach(function(item) {
            var step = document.getElementById(item);
            updateStep(step, 100);
        });
        setTimeout(function () {
            const url = window.location.href;
            window.location.href = url + (url.match(/\?/) ? '&' : '?') + 'q=' + Date.now();
        }, 10000);
    };

    var getStatus = function (callback) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '/maintenance/status.json?q=' + Date.now(), true);
        xhr.send();
        xhr.onreadystatechange = function() {
            if (this.readyState !== 4) {
                return;
            }
            if (this.status === 0) {
                window.location.reload();
            }
            callback(this);
        };
    };

    var timer = setInterval(function () {
        getStatus(function(xhr) {
            if (xhr.status === 404) {
                allDone(timer);
                return;
            }

            var data = JSON.parse(xhr.responseText);
            var step = document.getElementById(data.status);
            step.style.display = '';
            updateStep(step, data.progress, data.message);
        });
    }, 5000);

    // Init
    getStatus(function (xhr) {
       if (xhr.status !== 200) {
           return;
       }

       var data = JSON.parse(xhr.responseText);
       steps.some(function(item) {
           var step = document.getElementById(item);
           step.style.display = '';
           updateStep(step, item === data.status ? data.progress : 100, data.message);
           return item === data.status;
       });
    });
});
