define('bitbucket/internal/mirroring/placeholder', [
    'aui',
    'jquery',
    'bitbucket/util/navbuilder',
    'bitbucket/util/server',
    'bitbucket/internal/util/browser-window',
    'exports'
], function (
    ajs,
    $,
    nav,
    server,
    window,
    exports
) {

    'use strict';

    var location = window.location;
    var pollStateChange = function (state) {
        return server.poll({
            url: nav.rest("mirroring", "1.0").addPathComponents("upstreamServers").build(),
            pollTimeout: false, //no timeout
            interval: 30 * 1000, //30 seconds.
            tick: function (data) {
                //There is only zero or one upstream currently.
                if (data.size && data.values[0].state !== state) {
                    return true;
                }
                //undefined means re-poll.
            },
            statusCode: {
                '*' : false
            }
        });
    };

    var states = {
        initializing: function () {
            $(".mirror-initializing-spinner").spin('large');
            pollStateChange("initializing").done(function () {
                location.reload();
            }).fail(function (xhr) {
                if (xhr && xhr.status === 503) {
                    //The mirror plugin can Johnson the server if the URL is bad. It returns a 503 when this happens
                    //so we just reload the page to ensure the error is displayed.
                    location.reload();
                } else {
                    $(".mirror-initializing-spinner").spinStop();
                    $("#mirror-initializing-heading").text(ajs.I18n.getText('bitbucket.web.mirroring.connecting.lost.connection'));
                }
            });
        },
        pending: function () {
            pollStateChange("pending").done(function () {
                location.reload();
            });
        },
        unknown: function () {
            pollStateChange("unknown").done(function () {
                location.reload();
            });
        }
    };

    exports.onReady = function (state) {
        var callback = states[state];
        callback && callback.call(this);
    };
});