'use strict';

/* global angular:false */
/* global $:false */

angular.module('Application').controller('SystemController', ['$scope', '$location', '$interval', 'Client', function ($scope, $location, $interval, Client) {
    Client.onReady(function () { if (!Client.getUserInfo().admin) $location.path('/'); });

    $scope.config = Client.getConfig();
    $scope.ready = false;
    $scope.services = [];
    $scope.isRebootRequired = false;

    function refresh(serviceName, callback) {
        callback = callback || function () {};

        Client.getService(serviceName, function (error, result) {
            if (error) Client.error(error);

            var service = $scope.services.find(function (s) { return s.name === serviceName; });
            if (!service) $scope.services.push(result);

            service.status = result.status;
            service.config = result.config;
            service.memoryUsed = result.memoryUsed;
            service.memoryPercent = result.memoryPercent;

            callback(null, service);
        });
    }

    function refreshAll() {
        $scope.services.forEach(function (s) {
            refresh(s.name);
        });
    }

    $scope.reboot = {
        busy: false,

        show: function () {
            $scope.reboot.busy = false;

            $('#rebootModal').modal('show');
        },

        submit: function () {
            $scope.reboot.busy = true;

            Client.reboot(function (error) {
                $scope.reboot.busy = false;
                if (error) return Client.error(error);

                $('#rebootModal').modal('hide');
            });
        }
    };

    $scope.restartService = function (serviceName) {
        function waitForActive(serviceName) {
            refresh(serviceName, function (error, result) {
                if (result.status === 'active') return;

                setTimeout(function () { waitForActive(serviceName); }, 3000);
            });
        }

        $scope.services.find(function (s) { return s.name === serviceName; }).status = 'starting';

        Client.restartService(serviceName, function (error) {
            if (error) return Client.error(error);

            // show "busy" indicator for 3 seconds to show some ui activity
            setTimeout(function () { waitForActive(serviceName); }, 3000);
        });
    };

    $scope.serviceConfigure = {
        error: null,
        busy: false,
        service: null,

        // form model
        memoryLimit: 0,
        memoryTicks: [],

        show: function (service) {
            $scope.serviceConfigure.reset();

            $scope.serviceConfigure.service = service;
            $scope.serviceConfigure.memoryLimit = service.config.memory;

            // TODO improve those
            $scope.serviceConfigure.memoryTicks = [];

            // create ticks starting from manifest memory limit. the memory limit here is currently split into ram+swap (and thus *2 below)
            // TODO: the *2 will overallocate since 4GB is max swap that cloudron itself allocates
            $scope.serviceConfigure.memoryTicks = [];
            var npow2 = Math.pow(2, Math.ceil(Math.log($scope.config.memory)/Math.log(2)));
            for (var i = 256; i <= (npow2*2/1024/1024); i *= 2) {
                $scope.serviceConfigure.memoryTicks.push(i * 1024 * 1024);
            }

            $('#serviceConfigureModal').modal('show');
        },

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

            Client.configureService($scope.serviceConfigure.service.name, memoryLimit, function (error) {
                $scope.serviceConfigure.busy = false;
                if (error) {
                    $scope.serviceConfigure.error = error.message;
                    return;
                }

                refresh($scope.serviceConfigure.service.name);

                $('#serviceConfigureModal').modal('hide');
                $scope.serviceConfigure.reset();
            });
        },

        reset: function () {
            $scope.serviceConfigure.busy = false;
            $scope.serviceConfigure.error = null;
            $scope.serviceConfigure.service = null;

            $scope.serviceConfigure.memoryLimit = 0;
            $scope.serviceConfigure.memoryTicks = [];

            $scope.serviceConfigureForm.$setPristine();
            $scope.serviceConfigureForm.$setUntouched();
        }
    };

    Client.onReady(function () {
        Client.isRebootRequired(function (error, result) {
            if (error) console.error(error);

            $scope.isRebootRequired = !!result;

            Client.getServices(function (error, result) {
                if (error) return Client.error(error);

                $scope.services = result.map(function (serviceName) { return { name: serviceName }; });

                // just kick off the status fetching
                refreshAll();

                $scope.ready = true;
            });
        });
    });
}]);
