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

define(
    [
        'pim/job/common/edit/field/text',
        'webkuldam/template/validate-button',
        'oro/loading-mask',
        'oro/messenger',
    ],
    function (
        parentField,
        template,
        LoadingMask,
        messenger
    ) {
        return parentField.extend({
            fieldTemplate: _.template(template),
            events: {
                'click .validate': 'validate'
            },
            /**
             * {@inheritdoc}
             */
            validate: function () {
                // this.render();
                
                this.getRoot().trigger('pim_enrich:form:entity:pre_save', this.getFormData());
                this.showLoadingMask();
                $.ajax({
                    method: 'POST',
                    url: this.getSaveUrl(),
                    contentType: 'application/json',
                    data: JSON.stringify(this.getFormData())
                })
                .done(function(data){
                    messenger.notify(
                        'success', "FTP credentials and filePath is valid"
                        );
                    this.hideLoadingMask()
                }.bind(this))
                .fail(function (xhr){
                    var message = xhr.responseJSON && xhr.responseJSON.message ?
                                xhr.responseJSON.message :
                                _.__('pim_enrich.entity.ftp.error');
                    
                    messenger.notify(
                        'error', message
                        );
                    this.hideLoadingMask()

                }.bind(this))
                .always(function (){
                    this.hideLoadingMask()
                }.bind(this));
            },
            /**
             * Show the loading mask
             */
            showLoadingMask: function () {
                this.loadingMask = new LoadingMask();
                this.loadingMask.render().$el.appendTo(this.getRoot().$el).show();
            },

            /**
             * Hide the loading mask
             */
            hideLoadingMask: function () {
                this.loadingMask.hide().$el.remove();
            },
            /**
             * {@inheritdoc}
             */
            getSaveUrl: function () {
                var tab = null;
                
                var route = Routing.generate('webkul_ftp_rest_check');

                return tab ? route + '/' + tab : route;
            },

        });
    }
);