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

define('de_epages/shop/linkpicker/filemanagerview', [
    'jquery',
    'backbone',
    'ep',
    '$tmpl!de_epages/shop/linkpicker/filemanagerview',
    '$dict!../dictionary',
    'de_epages/mediagallery/ui/filemanagerdialog'
    /**
     * Filemanager view
     * @param  {Function}       $           jQuery
     * @param  {Function}       Backbone    Backbone
     * @param  {Function}       ep          Used for accessing config object
     * @param  {Function}       template    Template for rendering the filemanager view
     * @param  {Function}       dict        Dictionary
     * @return {Backbone View}              Filemanager view
     */
], function ($, Backbone, ep, template, dict) {
    'use strict';

    return Backbone.View.extend({

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

        /**
         * Template used for rendering
         * @type {Function}
         */
        template: template,

        /**
         * Data used in the template rendering process
         * @type {Object}
         */
        data: {},

        /**
         * File extensions that can be displayed
         * @type {Array}
         */
        displayableExt: ['.jpg', '.jpeg', '.png', '.gif'],

        /**
         * Path to placeholder that is used when file cannot be displayed
         * @type {String}
         */
        unknownExt: ep.config.javascriptRoot + '/de_epages/mediagallery/images/ico_unknowndocumentpreview.png',

        /**
         * Renders the filemanager view
         */
        render: function () {

            var self = this,
                renderedTemplate;

            this.$el.mediagalleryUiFilemanagerdialog({
                dialog: {
                    draggable: true,
                    buttons: [{
                        text: dict.translate('Apply'),
                        click: function () {
                            var element = self.$el.mediagalleryUiFilemanagerdialog('getSelectedElements')[0];

                            if (element) {
                                self.data.name = element.get('name').replace(element.get('extension'), "");
                                self.data.path = element.get('fullpath');
                                self.data.preview = self._getCorrectPreview(self.data.path);
                            }

                            $(this).uiDialog('close');
                            self._publishLinkData(self.data);

                        }
                    }, {
                        text: dict.translate('Cancel'),
                        click: function () {
                            $(this).uiDialog('close');
                        }
                    }]
                },
                filemanager: {}
            }).empty();

            renderedTemplate = this.template(self.data).dictParse(dict, true);

            // calling children() to omit template's root div which's necessary for getting {{elem}}s
            this.$el.html(renderedTemplate.children());

            $.extend(this, renderedTemplate.tmplItem().elements);

            return this;
        },

        /**
         * Determine the correct path of the file preview
         * @param  {String} _path [Path to the file that should be displayed]
         * @return {String}       [Path to the file (if displayable) or Path to a static placeholder]
         * @private
         */
        _getCorrectPreview: function (_path) {

            // see if we can display the extension, return path to placeholder otherwise
            var ext = _path.substr(_path.lastIndexOf('.'));
            return $.inArray(ext, this.displayableExt) === -1 ? this.unknownExt : _path;
        },

        /**
         * Sets the previe image and the label of the file
         * @param {String} _path [Path to the file]
         */
        setPreviewImage: function (_path) {

            if (_path) {
                this.data.name = _path.substr(_path.lastIndexOf('/')).slice(1);
                this.data.path = _path;
                this.data.preview = this._getCorrectPreview(_path);

                this.preview.empty().html('<img src="' + this.data.preview + '" />');
                this.previewLabel.empty().append(this.data.name);
            }
        },

        /**
         * Clears the image preview and its label
         */
        clearLinkData: function () {

            this.data = {};
            this.preview.empty();
            this.previewLabel.empty();
        },

        /**
         * Trigger the 'linkpicked'        event and publish name, path and preview and set the preview image
         * @param   {Object} _data [Contains the link data (name, path, preview)]
         * @private
         */
        _publishLinkData: function (_data) {
            this.setPreviewImage(_data.path);
            this.trigger('linkpicked', _data.name, _data.path, _data.preview);
        }
    });
});