define([
        '../app',
        '../html/config_edit_box_directive.html',
        '../functions/setEndOfContenteditable',
        '../functions/parseConfigItem',
        '../functions/unparseConfigItem'],
    function (
        app,
        template,
        setEndOfContenteditable,
        parseConfigItem,
        unparseConfigItem
    ) {
        editBoxController.$inject = ['$element', '$timeout', '$rootScope'];

        function editBoxController($element, $timeout, $rootScope) {
            /** @var {{rowItem: {value: {value: string}}, isFocused: {show: bool}}} controller */
            var controller = this;

            this.$onInit = function() {
                if (controller.preFormatted === undefined)
                    controller.preFormatted = true;
                controller.innerValue = parseConfigItem(controller.type, controller.rowItem);

                $timeout(function () {
                    var trueElement = angular.element($element).find('[contenteditable]');
                    trueElement.bind("blur", function () {
                        controller.hideBox();
                    });
                    trueElement.bind('paste', function (event) {
                        event.preventDefault();
                        var content = event.originalEvent.clipboardData.getData('text/plain');
                        var element = $('<div>' + content + '</div>');
                        $(this).text(element.text());
                    });
                    trueElement.focus();
                    setEndOfContenteditable(trueElement[0]);

                }, 0);
            };

            controller.hideBox = function () {
                controller.isFocused = false;
                controller.rowItem = unparseConfigItem(controller.type, controller.innerValue, controller.rowItem);
                $rootScope.$digest();
            };
        }

        app.directive('configEditBox', function () {
            return {
                restrict: 'E',
                bindToController: true,
                controllerAs: 'ctrl',
                scope: {
                    isFocused: "=",
                    type: "=",
                    rowItem: "=",
                    preFormatted: "@"
                },
                templateUrl: template,
                controller: editBoxController
            }
        });
    });
