/**
 * @author Sergei Lissovski <sergei.lissovski@modera.org>
 */
Ext.define('MF.activation.activities.BasicEditRecordWindowActivity', {
    extend: 'MF.activation.activities.AbstractActivity',

    requires: [
        'MF.Util'
    ],

    /**
     * ID this activity will have.
     *
     * @cfg {Function} id
     */
    /**
     * ExtJs direct object which has "get" and "update" methods. For more details on client-server communication protocal
     * please see [ModeraServerCrudBundle](https://github.com/modera/ModeraServerCrudBundle).
     *
     * @cfg {Object} directClass
     */
    /**
     * A fully qualified class name to use as UI for this activity. If you need more control over UI creation process
     * then see {@link #uiFactory}.
     *
     * @cfg {String} uiClass
     */
    /**
     * Allows to define a function that will be used to create a UI for this activity. The function will be invoked in
     * context of activity ( this will reference activity instance ).
     *
     * @cfg {Function} uiFactory
     */

    // override
    constructor: function(config) {
        MF.Util.validateRequiredConfigParams(this, config, ['id', 'directClass']);

        if (!config['uiClass'] && !config['uiFactory']) {
            throw Ext.String.format('%s.constructor(config): Either config.uiClass or config.uiFactory must be provided!');
        }

        this.callParent(arguments);
    },

    // override
    getId: function() {
        return this.id;
    },

    // protected
    getHydrationProfileId: function() {
        return this.getId();
    },

    // protected
    getFilterPropertyId: function() {
        return 'id';
    },

    // override
    doCreateUi: function(params, callback) {
        var me = this;

        var requestParams = {
            filter: [
                { property: this.getFilterPropertyId(), value: 'eq:' + params.id }
            ],
            hydration: {
                profile: this.getHydrationProfileId()
            }
        };

        this.directClass.get(requestParams, function(response) {
            var window = Ext.isFunction(me.uiFactory) ? me.uiFactory.apply(me) : Ext.create(me.uiClass);

            window.loadGroupedData(response.result);

            callback(window);
        });
    },

    // protected
    attachListeners: function(ui) {
        var me = this;

        ui.on('saveandclose', function(window) {
            var values = window.down('form').getForm().getValues();

            me.directClass.update({ record: values }, function(response) {
                if (response.success) {
                    if (me.section) {
                        me.section.fireEvent('recordsupdated', response['updated_models']);
                    }

                    window.close();
                } else {
                    window.showErrors(response);
                }
            });
        })
    }
});