(function () {
    var app = angular.module('myApp', ['ui.sortable', 'ui.toggle', 'nucleusConstants', 'corradeVersion']);
    app.controller('myCtrl', [ '$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
        $scope.logs = ["Corrade.log", "OpenMetaverse.log"];

        $scope.updateLog = true;
        $scope.tailLines = 25;
        $scope.selectedLog = '';
        $scope.logData = '';

        // Fetch the actual configuration.
        $scope.onLogSelected = function () {
            // cancel the timer if active
            if($scope.timer !== undefined)
                $timeout.cancel($scope.timer);

            if(!$scope.showElement)
                $scope.showElement = !$scope.showElement;

            $http({
                method: 'GET',
                url: 'log/' + $scope.selectedLog,
                transformResponse: function (data) {
                    let lines = parseInt($scope.tailLines);

                    if(isNaN(lines) || lines < 1)
                        lines = 1;

                    return data.split(/\r?\n/).reverse().slice(1, lines + 1).join("\n");
                }
            }).then(function successCallback(response, status) {
                if($scope.updateLog) {
                    $scope.logData = response.data;
                }
                // reload the log file periodically
                $scope.timer = $timeout(function(){
                    $scope.onLogSelected();
                },1000);
            }, function errorCallback(data, status) {
                // All hope is lost.
            });
        }
    }]);

})();
