/*globals define*/
/*jslint nomen: true*/

define('de_epages/shop/linkpicker/pagetreeview', [
    'jquery',
    'backbone',
    'ep',
    'jquery/jstree/ui',
    'jquery/jstree/themes',
    'jquery/jstree/json_data'
//'jquery/jstree'
/**
 * [description]
 * @param  {Function}       $           jQuery
 * @param  {Function}       Backbone    Backbone
 * @param  {Object}         ep          Used for accessing ep.config object
 * @return {Backbone view}              Pagetree view
 */
], function ($, Backbone, ep) {
    'use strict';

    return Backbone.View.extend({

        /**
         * Tag used for $el
         * @type {String}
         */
        tagName: 'div',

        /**
         * Events the view listens to
         * @type {Object}
         */
        events: {
            'click a': '_publishLinkData'
        },

        /**
         * Calling the jstree on the specified dom node
         * @return {Backbone view}
         */
        render: function () {

            this.$el.jstree({
                plugins: ['themes', 'json_data', 'ui'],
                themes: {
                    theme: 'bo',
                    dots: true,
                    icons: true
                },
                //config for tree json_data plugin
                json_data: {
                    ajax: {
                        url: '?',
                        type: 'POST',
                        dataType: 'json',
                        context: this,
                        data: $.proxy(this, '_generateTreeJSONData')
                    }
                }
            });

            return this;
        },

        clearLinkData: function () {
            // should be implemented as soon as the jstree gets a indicator for selection
        },

        /**
         * Fetches a tree layer from the server
         * @param   {String} _node  jstree instance
         * @return  {JSON}          tree data
         * @private
         */
        _generateTreeJSONData: function (_node) {

            var returnData = {
                ViewAction: 'JSONChildrenJSTree'
            };

            if (_node === -1) {
                returnData.WithParent = 1;
                returnData.ObjectID = ep.config.startpageId;
            } else {
                returnData.ObjectID = _node.data('jstree').id;
            }

            return returnData;
        },

        /**
         * Trigger the 'linkpicked' event and publish name and url
         * @param   {Event} _event [Event that is fired]
         * @private
         */
        _publishLinkData: function (_event) {

            _event.preventDefault();

            var leafNode = $(_event.currentTarget).parent(),
                url = leafNode.data('jstree').WebUrl,
                text = this.$el.jstree('get_text', leafNode);

            this.trigger('linkpicked', text, url);
        }
    });
});