'use strict';

/* global angular */
/* global $ */

// create main application module
var app = angular.module('Application', ['pascalprecht.translate', 'ngCookies', 'angular-md5', 'ui-notification', 'ui.bootstrap']);

app.controller('SetupController', ['$scope', 'Client', function ($scope, Client) {
    // Stupid angular location provider either wants html5 location mode or not, do the query parsing on my own
    var search = decodeURIComponent(window.location.search).slice(1).split('&').map(function (item) { return item.split('='); }).reduce(function (o, k) { o[k[0]] = k[1]; return o; }, {});

    $scope.client = Client;
    $scope.view = '';
    $scope.initialized = false;
    $scope.apiServerOrigin = '';
    $scope.webServerOrigin = '';
    $scope.setupToken = '';

    $scope.owner = {
        error: null,
        busy: false,

        email: '',
        displayName: '',
        username: '',
        password: '',

        submit: function () {
            $scope.owner.busy = true;
            $scope.owner.error = null;

            var data = {
                username: $scope.owner.username,
                password: $scope.owner.password,
                email: $scope.owner.email,
                displayName: $scope.owner.displayName,
                setupToken: $scope.setupToken
            };

            Client.createAdmin(data, function (error) {
                if (error && error.statusCode === 400) {
                    $scope.owner.busy = false;
                    $scope.owner.error = { username: error.message };
                    $scope.owner.username = '';
                    $scope.ownerForm.username.$setPristine();
                    setTimeout(function () { $('#inputUsername').focus(); }, 200);
                    return;
                } else if (error) {
                    $scope.owner.busy = false;
                    console.error('Internal error', error);
                    $scope.owner.error = { generic: error.message };
                    return;
                }

                setView('finished');
            });
        }
    };

    function redirectIfNeeded(status) {
        if ('develop' in search || localStorage.getItem('develop')) {
            console.warn('Cloudron develop mode on. To disable run localStorage.removeItem(\'develop\')');
            localStorage.setItem('develop', true);
            return;
        }

        // if we are here from the ip first go to the real domain if already setup
        if (status.adminFqdn && status.adminFqdn !== window.location.hostname) {
            window.location.href = 'https://' + status.adminFqdn + '/setup.html';
            return;
        }

        // if we don't have a domain yet, first go to domain setup
        if (!status.adminFqdn) {
            window.location.href = '/setupdns.html';
            return;
        }

        if (status.activated) {
            window.location.href = '/';
            return;
        }
    }

    function setView(view) {
        if (view === 'finished') {
            $scope.view = 'finished';
        } else {
            $scope.view = 'owner';
        }
    }

    function init() {
        Client.getStatus(function (error, status) {
            if (error) return Client.initError(error, init);

            redirectIfNeeded(status);
            setView(search.view);

            $scope.apiServerOrigin = status.apiServerOrigin;
            $scope.webServerOrigin = status.webServerOrigin;

            $scope.setupToken = search.setupToken;
            $scope.initialized = true;

            // Ensure we have a good autofocus
            setTimeout(function () {
                $(document).find("[autofocus]:first").focus();
            }, 250);
        });
    }

    init();
}]);
