'use strict';

var EventCreateController  = angular.module('events.controllers.create', [
    'system'
])
    .controller('EventCreateController', [
        '$scope',
        '$location',
        'System',
        'EventService',
        'ClassificationService',
        function ($scope, $location, System, EventService, ClassificationService) {
            $scope.event = { 
            };
            $scope.Labels = {};
      

            $(".tooltip").tooltip();
            $scope.query = {Alias: 'najave'}
            ClassificationService.query($scope.query)
                .then(function(data) {
                    $scope.classifications = [];
                    for (var i = 0; i < data.classifications.length; i++) {
                        $scope.classifications[i] = {
                            Alias: data.classifications[i].Alias,
                            Labels: []
                        };
                        $scope.classifications[i]['Labels'] = qusion.list.jsTree(data.classifications[i].Labels, "ID", "Name");
                    }
                });
            
            $scope.treeOptions = {
                selectMode: 2,
                dialogTitle: $scope.$resource('events.select_labels')
            };

            $scope.create = function () {
                $scope.event.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.event.Labels.push($scope.Labels[keys[i]][j]);
                    }

                }
                
                EventService.create($scope.event)
                    .then(function (response) {
                        if (response.Errors) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('utility.changeNotSave'));
                        } else {
                            $location.url('/events');
                            System.Message.success($scope.$resource('events.EventCreated'));
                        }
                    });
            };

            $scope.back = function () {
                $location.url('/events');
            };
        }
    ]);