'use strict';

define(
    [
        'jquery',
        'underscore',
        'oro/translator',
        'backbone',
        'webkuldam/template/select/asset-group',
        'pim/fetcher-registry',
        'pim/form-builder',
        'pim/security-context',
        'pim/media-url-generator',
        'bootstrap-modal'
    ], (
        $,
        _,
        __,
        Backbone,
        template,
        FetcherRegistry,
        FormBuilder,
        SecurityContext,
        MediaUrlGenerator
    ) => {
        return Backbone.View.extend({
            className: 'AknAssetGroupField',
            data: [],
            context: {},
            template: _.template(template),
            events: {
                'click .add-asset': 'updateAssets',
                'click .upload-assets': 'uploadAssets'
            },

            /**
             * {@inheritdoc}
             *
             * In the case where asset codes are integers, even if their order iscorrectly managed by the backend, the
             * fetcher will reorganize them, sorting them by code ascending. As "this.data" contains the codes in the
             * correct order, we reorder the assets according to this list of code.
             */
            render() {
            
                if(!this.data) {
                    this.data = [];
                }
                   
                
                FetcherRegistry.getFetcher('asset').fetchByIdentifiers(this.data).then(assets => {
                
                    let orderedAssets = [];
                    this.data.forEach(assetCode => {
                        orderedAssets = orderedAssets.concat(assets.filter(asset => asset.code === assetCode));
                    });
                    
                    this.$el.html(this.template({
                        assets: orderedAssets,
                        locale: this.context.locale,
                        scope: this.context.scope,
                        thumbnailFilter: 'thumbnail',
                        editMode: this.context.editMode,
                        MediaUrlGenerator: MediaUrlGenerator
                    }));

                    if ('view' !== this.context.editMode) {
                       
                        // this.$('.AknAssetCollectionField-list').sortable({
                        //     update: this.updateDataFromDom.bind(this)
                        // });
                    }
                    this.delegateEvents();
                });

                return this;
            },

            /**
             *
             */
            updateDataFromDom() {
                const assets = this.$('.AknAssetCollectionField-listItem')
                    .map((index, listItem) => listItem.dataset.asset)
                    .get();

                this.data = assets;
                this.trigger('collection:change', assets);
            },

            /**
             * Set data into the view
             *
             * @param {Array} data
             */
            setData(data) {
                this.data = data;
            },

            /**
             * Set context into the view
             *
             * @param {Object} context
             */
            setContext(context) {
                this.context = context;
            },

            /**
             * Launch the asset picker and set the assets after update
             */
            updateAssets() {
                this.manageAssets().then(assets => {
                    
                    
                    this.data = assets;

                    this.trigger('collection:change', assets);
                    this.render();
                });
                
            },

            /**
             * Open the modal to mass upload assets.
             */
            uploadAssets() {
                FormBuilder.build('pimee-asset-mass-upload').then(form => {
                    const routes = {
                        cancelRedirectionRoute: '',
                        importRoute: 'webkuldam_mass_upload_into_asset_collection_rest_import'
                    };

                    const entity = {
                        attributeCode: this.context.attributeCode,
                        identifier: this.context.entityIdentifier,
                        type: this.context.entityType
                    };

                    form.setRoutes(routes)
                        .setEntity(entity)
                        .setElement(this.$('.asset-mass-uploader'))
                        .render();
                });
            },

            /**
             * Launch the asset picker
             *
             * @return {Promise}
             */
            manageAssets() {
                const deferred = $.Deferred();
               
                FormBuilder.build('webkuldam-product-asset-select-form').then(form => {
                  
                    let modal = new Backbone.BootstrapModal({
                        className: 'modal modal--fullPage AknDamAssets modal--topButton',
                        modalOptions: {
                            backdrop: 'static',
                            keyboard: false
                        },
                        allowCancel: true,
                        okCloses: false,
                        title: '',
                        content: '',
                        cancelText: 'Cancel',
                        okText: __('confirmation.title')
                    });

                    
                    modal.open();

                    form.setImagePathMethod(function (item) {
                    
                        if(item && typeof(item.filePath) !== 'undefined' && item.filePath) {
                            return MediaUrlGenerator.getMediaShowUrl(item.filePath, 'thumbnail');
                        } else {
                            return null;
                        }
                    });
                    
                    form.setLabelMethod(item => item.description);
                    form.setElement(modal.$('.modal-body'))
                        .render()
                        .setItems(this.data);


                    modal.on('cancel', deferred.reject);
                    modal.on('ok', () => {
                        
                        const assets = _.sortBy(form.getItems(), 'code');
                        modal.close();
                        
                        deferred.resolve(assets);
                    });
                });
                

                return deferred.promise();
            },
        });
    }
);
