'use strict';

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

angular.module('Application').controller('AppsController', ['$scope', '$translate', '$interval', '$location', 'Client', function ($scope, $translate, $interval, $location, Client) {
    var ALL_DOMAINS_DOMAIN = { _alldomains: true, domain: 'All Domains' }; // dummy record for the single select filter
    var GROUP_ACCESS_UNSET = { _unset: true, name: 'Select Group' }; // dummy record for the single select filter

    $scope.installedApps = Client.getInstalledApps();
    $scope.tags = Client.getAppTags();
    $scope.states = [
        { state: '', label: 'All States' },
        { state: 'running', label: 'Running' },
        { state: 'stopped', label: 'Stopped' },
        { state: 'not_responding', label: 'Not Responding' }
    ];
    $scope.selectedState = $scope.states[0];
    $scope.selectedTags = [];
    $scope.selectedGroup = GROUP_ACCESS_UNSET;
    $scope.selectedDomain = ALL_DOMAINS_DOMAIN;
    $scope.filterDomains = [ ALL_DOMAINS_DOMAIN ];
    $scope.config = Client.getConfig();
    $scope.user = Client.getUserInfo();
    $scope.domains = [];
    $scope.appSearch = '';
    $scope.groups = [ GROUP_ACCESS_UNSET ];

    $translate(['apps.stateFilterHeader', 'apps.domainsFilterHeader', 'apps.groupsFilterHeader', 'app.states.running', 'app.states.stopped', 'app.states.notResponding']).then(function (tr) {
        if (tr['apps.domainsFilterHeader']) ALL_DOMAINS_DOMAIN.domain = tr['apps.domainsFilterHeader'];
        if (tr['apps.groupsFilterHeader']) GROUP_ACCESS_UNSET.name = tr['apps.groupsFilterHeader'];
        if (tr['apps.stateFilterHeader']) $scope.states[0].label = tr['apps.stateFilterHeader'];
        if (tr['app.states.running']) $scope.states[1].label = tr['app.states.running'];
        if (tr['app.states.stopped']) $scope.states[2].label = tr['app.states.stopped'];
        if (tr['app.states.notResponding']) $scope.states[3].label = tr['app.states.notResponding'];
    });

    $scope.$watch('selectedTags', function (newVal, oldVal) {
        if (newVal === oldVal) return;

        localStorage.selectedTags = newVal.join(',');
    });

    $scope.$watch('selectedDomain', function (newVal, oldVal) {
        if (newVal === oldVal) return;

        if (newVal._alldomains) localStorage.removeItem('selectedDomain');
        else localStorage.selectedDomain = newVal.domain;
    });

    $scope.appPostInstallConfirm = {
        app: {},
        message: '',
        confirmed: false,

        show: function (app) {
            $scope.appPostInstallConfirm.app = app;
            $scope.appPostInstallConfirm.message = app.manifest.postInstallMessage;
            $scope.appPostInstallConfirm.confirmed = false;

            $('#appPostInstallConfirmModal').modal('show');

            return false; // prevent propagation and default
        },

        submit: function () {
            if (!$scope.appPostInstallConfirm.confirmed) return;

            $scope.appPostInstallConfirm.app.pendingPostInstallConfirmation = false;
            delete localStorage['confirmPostInstall_' + $scope.appPostInstallConfirm.app.id];

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

    $scope.appInfo = {
        app: {},
        message: '',

        show: function (app) {
            $scope.appInfo.app = app;
            $scope.appInfo.message = app.manifest.postInstallMessage;

            $('#appinfoPostinstallMessage').collapse('hide');
            $('#appInfoModal').modal('show');

            return false; // prevent propagation and default
        }
    };

    $scope.showAppConfigure = function (app, view) {
        $location.path('/app/' + app.id + '/' + view);
    };

    Client.onReady(function () {
        setTimeout(function () { $('#appSearch').focus(); }, 1);

        // refresh the new list immediately when switching from another view (appstore)
        Client.refreshInstalledApps(function () {
            var refreshAppsTimer = $interval(Client.refreshInstalledApps.bind(Client, function () {}), 5000);
            $scope.$on('$destroy', function () {
                $interval.cancel(refreshAppsTimer);
            });
        });

        if (!$scope.user.isAtLeastAdmin) return;

        // load local settings and apply tag filter
        if (localStorage.selectedTags) {
            if (!$scope.tags.length) localStorage.removeItem('selectedTags');
            else $scope.selectedTags = localStorage.selectedTags.split(',');
        }

        Client.getGroups(function (error, result) {
            if (error) Client.error(error);

            $scope.groups = [ GROUP_ACCESS_UNSET ].concat(result);
        });

        Client.getDomains(function (error, result) {
            if (error) Client.error(error);

            $scope.domains = result;
            $scope.filterDomains = [ALL_DOMAINS_DOMAIN].concat(result);

            if (localStorage.selectedDomain) $scope.selectedDomain = $scope.filterDomains.find(function (d) { return d.domain === localStorage.selectedDomain; }) || ALL_DOMAINS_DOMAIN;
        });
    });

    $('.collapse').on('shown.bs.collapse', function(){
        $(this).parent().find('.fa-angle-right').removeClass('fa-angle-right').addClass('fa-angle-down');
    }).on('hidden.bs.collapse', function(){
        $(this).parent().find('.fa-angle-down').removeClass('fa-angle-down').addClass('fa-angle-right');
    });

    $('.modal-backdrop').remove();
}]);
