define(['../app', '../html/config_item_directive.html', '../functions/getType', '../functions/itemCmp'], function(app, template, getType, itemCmp){
    itemController.$inject = ['restCollection', '$element', '$timeout'];
    function itemController(restCollection, $element, $timeout) {
        var ctrl = this;

        this.$onInit = function() {
            ctrl.getType = getType;
            ctrl.revertButton = null;
            ctrl.type = ctrl.getType(ctrl.item.value);
            ctrl.hasDesc = 'desc' in ctrl.item;

            ctrl.reset();

            ctrl.valueCompare = itemCmp;

            $timeout(function(){
                ctrl.revertButton = $element.find('.revert-button');
            },0);
        };

        ctrl.revert = function($event)
        {
            $event.preventDefault();
            ctrl.item.value = ctrl.oldValue;
            ctrl.item.marked_for_death = false;
            ctrl.type = ctrl.getType(ctrl.item.value);
            ctrl.revertButton.trigger('revert');
        };

        ctrl.delete = function($event)
        {
            $event.preventDefault();
            ctrl.item.marked_for_death = true;
        };

        ctrl.reset = function(){
            ctrl.oldValue = ctrl.item.value;
        };

        ctrl.checkDirty = function() {
            return (!ctrl.valueCompare(ctrl.oldValue, ctrl.item.value) && !ctrl.item.is_new);
        };

        ctrl.checkFilter = function() {
            return ctrl.item.key.toLowerCase().indexOf(ctrl.filterText.toLowerCase()) >= 0;
        };

        ctrl.checkDeletable = function() {
            return !ctrl.item.readonly && !ctrl.item.marked_for_death && ctrl.item.origin === "json";
        };

        ctrl.checkRevertable = function() {
            return ctrl.checkDirty() || ctrl.item.marked_for_death;
        };
    }

    app.directive('configItem', function () {
        return {
            restrict: 'E',
            replace: true,
            bindToController: true,
            scope: {
                item: '=',
                filterText: '@'
            },
            controllerAs: 'ctrl',
            templateUrl: template,
            controller: itemController
        }
    });
});
