'use strict';

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

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

    $scope.config = Client.getConfig();
    $scope.user = Client.getUserInfo();
    $scope.apps = Client.getInstalledApps();

    $scope.feedback = {
        error: null,
        result: null,
        busy: false,
        subject: '',
        type: 'ticket',
        description: '',
        appId: '',
        altEmail: ''
    };

    $scope.sshSupportEnabled = false;
    $scope.subscription = null;

    function resetFeedback() {
        $scope.feedback.subject = '';
        $scope.feedback.description = '';
        $scope.feedback.type = 'ticket';
        $scope.feedback.appId = '';
        $scope.feedback.altEmail = '';

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

    $scope.submitFeedback = function () {
        $scope.feedback.busy = true;
        $scope.feedback.result = null;
        $scope.feedback.error = null;

        Client.createTicket($scope.feedback.type, $scope.feedback.subject, $scope.feedback.description, $scope.feedback.appId, $scope.feedback.altEmail, function (error, result) {
            if (error) {
                $scope.feedback.error = error.message;
            } else {
                $scope.feedback.result = result;
                resetFeedback();
            }

            $scope.feedback.busy = false;
        });
    };

    $scope.toggleSshSupport = function () {
        Client.enableRemoteSupport(!$scope.sshSupportEnabled, function (error) {
            if (error) return $scope.error(error);

            $scope.sshSupportEnabled = !$scope.sshSupportEnabled;
        });
    };

    function getSubscription() {
        Client.getSubscription(function (error, result) {
            if (error && error.statusCode === 412) return; // not yet registered
            if (error) return console.error(error);

            $scope.subscription = result;
        });
    }

    Client.onReady(function () {
        Client.getRemoteSupport(function (error, enabled) {
            if (error) return console.error(error);

            $scope.sshSupportEnabled = enabled;

            getSubscription();
        });
    });

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