'use strict';

define([
    'underscore',
    'pim/form/common/edit-form',
    'webkuldam/template/form/dam-tags',
    'pim/fetcher-registry',
    'jquery.select2',
], function (
    _,
    BaseEditForm,
    fieldTemplate,
    fetcherRegistry
) {
    return BaseEditForm.extend({
        fieldTemplate: _.template(fieldTemplate),
        events: {
            'change .damtag': 'updateState',

        },
        empty: ['No data found'],
        data: ['Select Tags'],
        asset: [],
        damtags: null,
        firstTime: null,

        /**
         * {@inheritdoc}
         */

        render: function () {
            var data = this.getFormData();
            
            var tag = 'undefined' !== typeof data['tag'] ?  data['tag'] : [];
            var damtags;
            if(this.damtags){
                damtags = this.damtags;
            }
            
            fetcherRegistry.getFetcher('dam-tags').fetchAll()
            .then(function (damtags) {
                
                BaseEditForm.prototype.configure.apply(this, arguments);
                this.$el.html(this.fieldTemplate({
                    config: damtags,
                    events: this.delegateEvents(),
                    asset : tag,
                }));

                var elem = this.$('#tags-select');
                elem.select2({
                    tags: damtags,
                    tokenSeparators: [',', ' ', ';'],
                    allowClear: true,
                    multiple: true,
                       
                });
                

                
                
            }.bind(this));
            
            

        },

        updateState: function(event) {
            
            var data = this.getFormData();
            this.asset = [];
            this.asset = 'undefined' !== typeof data['tag'] ?  data['tag'] : [];

            if(event.removed !== undefined){
                for (var key in this.asset) {
                    if (this.asset[key] == event.removed.text) {
                        this.asset.splice(key, 1);
                    }
                }
            }
            
            $.each(event.val, function(key,val){
                
                var id = this.asset.length + 1;
                var found = this.asset.some(function (el) {
                   
                    return el === val;
                });
                if(!found) {
                    this.asset.push(val);
                }
            }.bind(this))
            
            
            $.ajax({
                method: 'POST',
                url: Routing.generate('webkuldam_tag_create'),
                contentType: 'application/json',
                data: JSON.stringify(this.asset)
            })
            .then()
            .fail()
            if(data){
                data['tag'] = this.asset;
            }
            this.setData(data);
            
            
            // this.render();
        },
    });
});
