// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

Ext.define('Shopware.apps.ViisonCommonData.proxy.writer.WriterWithSupportForHasOneAssociations', {

    extend: 'Ext.data.writer.Json',

    /**
     * @override
     *
     * Adds support for hasOne associations by ensuring that model data joined via a hasOne
     * association will as well be part of the payload generated by the data writer.
     */
    setRecordAssociationData: function (record, data) {
        this.callParent(arguments);

        record.associations.each(function (association) {
            if (association.type === 'hasOne') {
                var associatedData = [];

                if (record[association.getterName]) {
                    var associatedRecord = record[association.getterName]();
                    if (associatedRecord instanceof Ext.data.Model) {
                        associatedData = this.getRecordFieldData(associatedRecord);

                        // Check if the record has associations, if this is the case, call recursive
                        if (associatedRecord.associations && associatedRecord.associations.length > 0) {
                            this.setRecordAssociationData(associatedRecord, associatedData);
                        }
                    }
                }

                data[association.associationKey] = associatedData;
            }
        }, this);
    },

});
