define(['../app', '../html/config_add_item_directive.html', '../functions/getType'], function(app, template, getType){
    addItemController.$inject = ["growl.service"];
    function addItemController(growl){
        var ctrl = this;

        this.$onInit = function() {
            ctrl.showEdit = false;
            ctrl.innerName = '';

            ctrl.reset();
        };

        ctrl.reset = function() {
            ctrl.item = {key:"", value:"", is_new: true};
            ctrl.type = getType(ctrl.item.value);
        };

        ctrl.hideBox = function(){
            ctrl.showEdit = false;
            ctrl.item.key = ctrl.innerName;
            $rootScope.$digest();
        };

        ctrl.addItem = function($event)
        {
            $event.preventDefault();
            if(ctrl.item.key.trim() !== '')
            {
                var namesakes = ctrl.items.filter(function(elem){return elem.key === ctrl.item.key;});
                if(namesakes.length === 0)
                {
                    ctrl.items.push(ctrl.item);
                    ctrl.reset();
                }
            }else
            {
                growl.showError("You must enter a name for the new object");
            }

        }
    }

    app.directive('configAddItem', function() {
        return {
            restrict: 'E',
            bindToController: true,
            controllerAs: 'ctrl',
            replace: true,
            scope: {
                items: "="
            },
            templateUrl: template,
            controller: addItemController
        };
    });
});
