let waitForSpinner = function () {
    let def = $.Deferred();
    let interval = setInterval(function () {
        if ($('#globalSpinner').css('display') == 'none') {
            clearInterval(interval);
            def.resolve();
        }
    }, 1000);
    return def;
};

let hostUrl;
if (window.localStorage.getItem('tourStarted') == 'true' && window.localStorage.getItem('tour_end') != 'yes') {
    $.ajax({
        url: "/astrolabe/host",
        async: false,
        type: 'POST',
        data: {page: 1, count: 1},
        dataType: 'json',
        success: function (data) {
            // if no hosts found then open page with undefined hostkey
            // which still shows host info page without specific host data
            hostUrl = `/hosts/${data[0].id ?? 'undefined'}`;
        }
    });
}

const addBackdrop = () => {
    if (!document.getElementById('backdrop')) {
        let backdrop = document.createElement("div");
        backdrop.innerHTML = `<div
                                id="backdrop"
                                title="The UI is not active while the tour guide"
                                style="top: 0; left: 0; height: 100vh; width: 100vw; position: absolute; z-index: 1070;"
                                ></div>`;
        document.body.append(backdrop);
    }
}

const removeBackdrop = () => {
    if (document.getElementById('backdrop')) {
        document.getElementById('backdrop').remove()
    }
}



var tourGuide = new Tour({
    backdrop: true,
    backdropPadding: 5,
    onShown: function () {
        // do not allow to use the UI while the tour guide is active
        addBackdrop();
    },
    onEnd: function () {
        window.location.href = '/dashboard';
        removeBackdrop();
    },
    template: '<div class="popover" role="tooltip"> ' +
        '<div class="arrow"></div> ' +
        '<h3 class="popover-title"></h3> ' +
        '<div class="popover-content"></div> ' +
        '<div class="popover-navigation"> <div class="btn-group  pull-left"> ' +
        '<button class="btn btn-sm btn-default" data-role="prev"><i class="icon-arrow-left"></i> Prev</button> ' +
        '<button class="btn btn-sm btn-default" data-role="next">Next <i class="icon-arrow-right"></i></button></div>' +
        '<div class="btn-group  pull-right"> ' +
        '<button class="btn btn-sm pause-button" data-role="pause-tour"><i class="icon-pause"></i> Pause</button> ' +
        '<button class="btn btn-sm  end-button" data-role="end"><i class="icon-stop"></i> End tour</button> </div>  </div> '
});

const openDropdownMenu = function () {
    let def = $.Deferred();

    let interval = setInterval(function () {
        if (
            $('#globalSpinner').css('display') == 'none' &&
            $('.pull-right.dropdown.open').length > 0
        ) {
            clearInterval(interval);
            def.resolve();
        } else {
            $('#dropdownMenu').click();
        }
    }, 1000);
    return def.promise();
}

const waitElementLoading = function (element) {
    let def = $.Deferred();
    let interval = setInterval(function () {
        if ($(element).is(":visible") == true) {
            clearInterval(interval);
            def.resolve();
        }
    }, 1000);
    return def.promise();
}

let steps = [
    {
        element: "li#build_app",
        title: "The new CFEngine Build application",
        content: "Allows you to automate and make changes without writing policy.",
        placement: "right",
        path: "/dashboard#/index"
    },
    {
        element: "li#groups_app",
        title: "The new Groups application",
        content: "Allows you to create dynamic host groups based on inventory filters.",
        placement: "right",
        path: "/dashboard#/index"
    },
    {
        element: "div[ng-click=\"initComplianceForm();\"]",
        title: "New compliance report widgets",
        content: "New compliance report widgets are available for use on dashboards.",
        placement: "left",
        path: "/dashboard#/index",
        onShow: function () {
            let def = $.Deferred();
            let interval = setInterval(function () {
                if (
                    $('#globalSpinner').css('display') == 'none' &&
                    $('div[ng-click="initComplianceForm();"]').is(":visible") == true
                ) {
                    clearInterval(interval);
                    def.resolve();
                } else {
                    $('.widget.empty a').click();
                }
            }, 1000);
            return def.promise()
        }
    }
];

steps.map(step => {
    step.onRedirectError = function (tour) {
        tour.next();
    };
    return step;
})

tourGuide.addSteps(steps);

if (window.localStorage.getItem('tourStarted') === 'true' && window.localStorage.getItem('tourPaused') !== 'true') {
    // in 3.23.0 we disable the tour, needs work
    //tourGuide.init().start();
    window.localStorage.setItem('tour_end', 'yes');
}


$(document).ready(function () {
    let resumeButtonHtml = '<button class="btn btn-large resume-tour-guide"><i class="icon-play "></i> Resume tour guide</button>';
    $(document).on('click', '[data-role="pause-tour"]', function () {
        $('.tour-tour').css('visibility', 'hidden');
        $('.tour-backdrop').css('visibility', 'hidden');
        window.localStorage.setItem('tourPaused', 'true');
        removeBackdrop();
        $('body').append(resumeButtonHtml)
    });

    if (window.localStorage.getItem('tourPaused') === 'true') {
        $('body').append(resumeButtonHtml)
    }

    $(document).on('click', '.resume-tour-guide', function () {
        window.localStorage.setItem('tourPaused', 'false');
        window.localStorage.removeItem('tour_redirect_to');
        tourGuide.init().start(true);
        $('.tour-tour').css('visibility', 'visible');
        $('.tour-backdrop').css('visibility', 'visible');
        $('.resume-tour-guide').remove();
    });
});
