define([
    'Magento_Ui/js/form/element/abstract',
    'Magento_Ui/js/lib/view/utils/async',
    'filoblu_esb_highligtht'
], function (Abstract, $, hljs) {
    return Abstract.extend({
        defaults: {
            template: 'ui/form/field',
            elementTmpl: 'FiloBlu_Esb/ui/form/element/ace',
            showSpinner: false,
            loading: false,
            additionalClasses : 'filoblu_esb_code_block'
        },

        /**
         * Initializes component, invokes initialize method of Abstract class.
         *
         *  @returns {Object} Chainable.
         */
        initialize: function () {

            let self = this;
            $.async({
                component: this,
                selector: 'pre'
            }, function (node) {

               if (self.isJson()) {
                   self.value(JSON.stringify(JSON.parse( self.value()), null, 4));
                }

                hljs.highlightBlock(node);
            });
            return this._super();
        },

        isJson: function () {
            let value = this.value();
            if (typeof value !== 'string') {
                return false;
            }

            try {
                const result = JSON.parse(value);
                const type = Object.prototype.toString.call(result);
                return type === '[object Object]'
                    || type === '[object Array]';
            } catch (err) {
                return false;
            }
        }
    });
});