'use strict';

/** 
 * @controller UserEditController
 * @property scope 
 * @property route
 * @property location
 * @property filter
 * @property System
 * @property UserService
 * @property Resource
 */

angular.module('users.controllers.edit', [
    'system'
])
    .controller('UserEditController', [
        '$scope',
        '$route',
        '$location',
        '$filter',
        'System',
        'UserService',
        'ClassificationService',
        function($scope, $route, $location, $filter, System, UserService, ClassificationService) {
            $scope.Id = $route.current.params["id"];

            $(".tooltip").tooltip();

            /**
            *@property view
            *@description Name of current view.
            */
            $scope.view = 'basic';

            $scope.Labels = {};

            /**
            *@property profilePhoto
            *@descritpion path to profile image.
            */
            $scope.profilePhoto = '/Areas/Qusion/Style/no-photo.png';

            /**
            *@property upload
            */
            $scope.upload = { };

            /**
            *@property uploadOption
            */
            $scope.uploadOption = {
                extensions: ['jpg', 'jpeg', 'png', 'gif'],
                multiple: false,
                doneall: function(e, data) {
                    angular.extend($scope.user, data.result);
                    $scope.upload.clear();
                    $scope.uploadDialog.dialog("close");
                    System.Message.success($scope.$resource('users.image_changed'));
                    $scope.$apply();
                },
                failedUpload: function (e, data) {
                    System.Message.error(data.MaxSize);
                    $scope.$apply();
                }
            };

            /**
            * @method init
            * @description This load all initial data.
            */
            $scope.init = function() {
                UserService.getEdit($scope.Id)
                    .then(function (data) {
                        $scope.user = data;
                        for (var i = 0; i < $scope.user.Labels.length; i++) {
                            if ($scope.Labels[data.Labels[i].Classification] == undefined) {
                                $scope.Labels[data.Labels[i].Classification] = new Array();
                            }
                            $scope.Labels[data.Labels[i].Classification].push(data.Labels[i]);
                        }
                    });

                ClassificationService.getByAlias("team")
                    .then(function (data) {
                        $scope.classification = {
                            Alias: data.Alias,
                            team: []
                        };
                        $scope.classification = qusion.list.jsTree(data.Labels, "ID", "Name");
                    });

                UserService.getRoles().then(function(data) {
                    $scope.roles = data;
                });
            };

            $scope.treeOptions = {
                selectMode: 2,
                dialogTitle: $scope.$resource('users.select_teams')
            };

            /**
            * @method update
            * @description UserService updates User data after successful edit
            */
            $scope.update = function () {
                $scope.user.Labels = [];
                console.log($scope.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.update($scope.user)
                    .then(function (response) {
                        if (response.Errors) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('utility.changeNotSave'));
                        } else {
                            System.Message.success($scope.$resource('users.UserChanged'));
                            $location.url('/users');
                        }
                    });
            };

            /**
            * @method view
            * @description Set current view on page.
            */
            $scope.setView = function(view) {
                $scope.view = view;
            };

            /**
            *@method changePassword
            *@description Change user password.
            */
            $scope.changePassword = function() {
                $scope.password.ID = $scope.Id;
                UserService.changePassword($scope.password).then(function(response) {
                    if (response.Errors) {
                        $scope.errors = response.Errors;
                        System.Message.error("Промјена није снимљена.");
                    } else {
                        System.Message.success("Пасворд успјешно промјењен.");
                    }
                });
            };

            /**
            *@method changeImge
            *@descritoion Open dialog for changing user profile image.
            */
            $scope.changeImge = function() {
                $scope.uploadDialog.dialog("open");
            };

            /**
            *@property uploadDialog
            */
            $scope.ui.uploadDialog = {
                width: 700,
                title: "Промјена слике профила",
                create: function() {
                    $scope.uploadDialog = $(this);
                }
            };
            
            /**
            *@method cancelEdit Close dialog and clear edit dialog.
            */
            $scope.cancelEdit = function () {
                $scope.upload.clear();
                $scope.uploadDialog.dialog("close");
            };

            /**
          *@method cancelEdit Close dialog and clear edit dialog.
          */
            $scope.zatvori = function () {
                $scope.init();
                $scope.uploadDialog.dialog("close");
            };
            /**
            * @action back returns to location /users
            */
            $scope.back = function() {
                $location.url('/users');
            };

            $scope.$watch("user.AvatarID", function(value) {
                if (value) {
                    $scope.profilePhoto = '/qusion/image/thumb/' + value + '?width=230';
                }
            });

            /**
            *@method startUpload
             *@description Start upload process.
            */
            $scope.save = function () {
                $timeout(function () {
                    $scope.upload.send();
                }, 100);
                $scope.init();
            };
            $scope.init();
        }
    ]);