'use strict';
/**
 * Password view extension
 *
 * @author    Aman Srivastava <aman.srivastava462@webkul.com>
 * @copyright 2019 Webkul Soft. Pvt. Ltd. (https://webkul.com)
 */

define(
    [
        'underscore',
        'pim/job/common/edit/field/field',
        'dam/template/job/common/directory_asset',
        'pim/fetcher-registry',
        'jquery.select2',
    ],
    function (
        _,
        BaseField,
        fieldTemplate,
        fetcherRegistry
    ) {
        return BaseField.extend({
            fieldTemplate: _.template(fieldTemplate),
            events: {
                'change select': 'updateState',
            },

            render: function () {          
                
                if(typeof(this.config.fetcher) !== 'undefined' && this.config.fetcher) {
                    var self = this;
                    fetcherRegistry.getFetcher(self.config.fetcher).fetchAll()
                    .then(function (data) {   
                        self.config.options = data;
                        
                        BaseField.prototype.render.apply(self, arguments);
                        var elem = self.$('.select2'); 
                        elem.select2();
                        elem.on("change", function (e) {
                            self.updateState();
                            self.parent.render(); 
                            
                        });

                    });
                    
                } else {

                    BaseField.prototype.render.apply(this, arguments);
                    var elem = this.$('.select2'); 
                    elem.select2();
                    elem.on("change", function (e) {
                        this.updateState();
                        this.parent.render(); 
                        
                    }.bind(this));
                }
            },

            /**
             * Get the field dom value
             *
             * @return {string}
             */
            getFieldValue: function () {
                return this.$('select').val();
            },
        });
    }
);