'use strict';

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

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

    $scope.installedApps = Client.getInstalledApps();
    $scope.tags = Client.getAppTags();
    $scope.selectedTags = [];
    $scope.selectedDomain = ALL_DOMAINS_DOMAIN;
    $scope.filterDomains = [ ALL_DOMAINS_DOMAIN ];
    $scope.config = Client.getConfig();
    $scope.user = Client.getUserInfo();
    $scope.domains = [];

    $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.showAppConfigure = function (app, view) {
        $location.path('/app/' + app.id + '/' + view);
    };

    Client.onReady(function () {
        Client.refreshInstalledApps(function () {}); // refresh the new list immediately when switching from another view (appstore)

        var refreshAppsTimer = $interval(Client.refreshInstalledApps.bind(Client, function () {}), 5000);
        $scope.$on('$destroy', function () {
            $interval.cancel(refreshAppsTimer);
        });

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

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

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

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