// Copyright 1999-2017. Plesk International GmbH. All Rights Reserved.

function updateSessionStatus(session_id, sessionStatusInfo)
{
    var blockNotStarted = sessionElement(session_id, 'block-not-started');
    var blockInProgress = sessionElement(session_id, 'block-in-progress');
    var blockAllMigrated = sessionElement(session_id, 'block-all-migrated');
    var blockMigrated = sessionElement(session_id, 'block-migrated');
    var allBlocks = [blockNotStarted, blockInProgress, blockAllMigrated, blockMigrated];

    if (!sessionStatusInfo.started) {
        showOnly(allBlocks, blockNotStarted);
    } else if (sessionStatusInfo.queueSubscriptions > 0) {
        showOnly(allBlocks, blockInProgress);
        var progressPercentage = Math.round(
            100 * sessionStatusInfo.queueFinishedSubscriptions / sessionStatusInfo.queueSubscriptions
        );
        sessionElement(session_id, 'progress-bar').setStyle(
            {'width': progressPercentage + "%"}
        );
        sessionElement(session_id, 'text-in-progress').update(
            formatMessage(
                MESSAGE_SUBSCRIPTIONS_IN_PROGRESS,
                sessionStatusInfo.queueFinishedSubscriptions,
                sessionStatusInfo.queueSubscriptions
            )
        );
    } else if (sessionStatusInfo.totalSourceSubscriptions == sessionStatusInfo.totalMigratedSubscriptions) {
        showOnly(allBlocks, blockAllMigrated);
        sessionElement(session_id, 'text-all-migrated').update(
            formatMessage(MESSAGE_ALL_SUBSCRIPTIONS_MIGRATED, sessionStatusInfo.totalSourceSubscriptions)
        );
    } else {
        showOnly(allBlocks, blockMigrated);
        sessionElement(session_id, 'text-migrated').update(
            formatMessage(MESSAGE_SUBSCRIPTIONS_MIGRATED, sessionStatusInfo.totalMigratedSubscriptions)
        );
    }
}

function periodicUpdateSessionStatus(session_id)
{
    new Ajax.Request(URL_GET_SESSION_STATUS + '/session/' + session_id, {
        onSuccess: function(response) {
            var sessionStatusInfo = response.responseText.evalJSON();
            updateSessionStatus(session_id, sessionStatusInfo);
            if (sessionStatusInfo.queueSubscriptions > 0) {
                // continue polling status for session in progress, don't poll status for all the others as
                // it is unlikely that they will be started, and it could take much time to poll status
                // of all sessions
                setTimeout(function () {
                    periodicUpdateSessionStatus(session_id)
                }, SESSION_PROGRESS_UPDATE_INTERVAL);
            }
        },
        onFailure: function() {
            setTimeout(function () {
                periodicUpdateSessionStatus(session_id)
            }, SESSION_PROGRESS_UPDATE_INTERVAL);
        }
    });
}

function sessionElement(session_id, element_id)
{
    return $(element_id + "-" + session_id);
}