define(['../app', '../html/config_array_edit_directive.html', 'jsoneditor', 'jsoneditor/dist/jsoneditor.min.css'], function(app, template, JSONEditor){
    arrayEditController.$inject = ['$element', '$timeout'];
    function arrayEditController($element, $timeout){
        var ctrl = this;

        this.$onInit = function() {
            ctrl.container = $element.find('.json-editor');
            ctrl.container = ctrl.container[0];

            ctrl.edit = false;

            var options = {
                mode: 'view'
            };

            $timeout(function(){
                ctrl.editor = new JSONEditor(ctrl.container, options);
                ctrl.editor.set(ctrl.item.value);
            }, 0);

            $element.closest('.tr').bind('revert', function(){
                ctrl.editor.set(ctrl.item.value);
            });
        };

        ctrl.makeEditable = function($event){
            ctrl.editor.setMode('tree');
            $event.preventDefault();
            ctrl.edit = true;
        };
        ctrl.makeUneditable = function($event){
            ctrl.editor.setMode('view');
            $event.preventDefault();
            ctrl.edit = false;
            ctrl.item.value = ctrl.editor.get();
        };
    }

    app.directive('configArrayEdit', function() {
        return {
            restrict: 'E',
            bindToController: true,
            controllerAs: 'ctrl',
            replace: true,
            scope: {
                item: "=",
                editable: '@'
            },
            templateUrl: template,
            controller: arrayEditController
        };
    });
});
