'use strict';

/** 
 * @controller UserCreateController
 * @property scope 
 * @property location
 * @property filter
 * @property System
 * @property UserService
 * @property Resource
 */

angular.module('users.controllers.create', [
    'system'
])
    .controller('UserCreateController', [
        '$scope',
        '$location',
        '$filter',
        '$route',
        'System',
        'UserService',
        'ClassificationService',
        function ($scope, $location, $filter, $route, System, UserService, ClassificationService) {
            /**
            *@property errors
            */
            $scope.errors = {};
            $scope.user = { };
            $scope.Labels = { team: [] };
            
            $(".tooltip").tooltip();

            /**
            * @method init
            * @description This load all initial data.
            */
            $scope.init = function() {
                UserService.getRoles().then(function(data) {
                    $scope.roles = data;

                });

                ClassificationService.getByAlias("team")
                    .then(function (data) {
                        $scope.classification = qusion.list.jsTree(data.Labels, "ID", "Name");;
                    });
            };
            
            $scope.treeOptions = {
                selectMode: 2,
                dialogTitle: $scope.$resource('users.select_teams')
            };

            /**
            * @method create
            * @description UserService creates new user
            */
            $scope.create = function () {
                $scope.user.Labels = [];
                var keys = (function (obj) {
                    var k = [], x;
                    for (x in obj) {
                        k.push(x);
                    }
                    return k;
                })($scope.Labels);

                for (var i = 0; i < keys.length; i++) {
                    for (var j = 0; j < $scope.Labels[keys[i]].length; j++) {
                        $scope.user.Labels.push($scope.Labels[keys[i]][j]);
                    }
                }
                
                UserService.create($scope.user)
                    .then(function (response) {
                        if (response.Errors) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('users.UserCreatedError'));
                        }else {
                            $location.url('/users');
                            System.Message.success($scope.$resource('users.UserCreated'));
                        }
                    });
            };
            
            /**
            *@action back
            *@description returns to location /users
            */
            $scope.back = function () {
                $location.url('/users');
            };

            $scope.init();

        }
    ]);