/* global AJS:false */
AJS.test.require([
    'com.atlassian.bitbucket.server.bitbucket-web:project-model',
    'com.atlassian.bitbucket.server.bitbucket-it-javascript:js-test-utils'
], function () {

    // Test Project Model integration with the REST API.

    var Project = require('bitbucket/internal/model/project');
    var ajax = require('bitbucket/internal/util/ajax');
    var nav = require('bitbucket/util/navbuilder');
    var AuthManager = require('js-test-utils/auth-manager');
    var auth = new AuthManager();
    var projectsUrl = nav.allProjects().withParams({start: 0, limit: 5}).build();


    module('model-project', {
        setup: function(){
            auth.loginAsAdmin();
        },
        teardown: function() {
            auth.logout();
        }
    });

    asyncTest("API to Model", function () {
        //First get a list of some of the projects.
        var xhr = ajax.rest({
            url: projectsUrl,
            '*': function() {
                return false;
            }
        });

        xhr
            .promise()
            .fail(function (xhr, status, message) {
                ok(false, 'Failed to retrieve projects from "' + projectsUrl + '" because: "' + status + ':' + message + '"');
                start();
            })
            .done(function (result, status, xhr) {
                start();

                ok(result && result.size > 0, 'more than 0 projects are retrieved');

                if (result && result.size > 0) {
                    // Pick a random project from the list we retrieved
                    var randomProj = result.values[ Math.floor(Math.random() * result.values.length) ];
                    ok(typeof randomProj === 'object', 'the selected project is an object');

                    var proj = new Project(randomProj);
                    ok(proj instanceof Project, 'project is valid Project model');
                }
            });

    });
});
