// 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.ViisonCommonConfigDocument.view.form.Document', {

    override: 'Shopware.apps.Config.view.form.Document',

    /**
     * @override
     */
    constructor: function () {
        this.viisonRelevantDocumentNames = ViisonCommonApp.getConfig('relevantDocumentNames', 'ViisonCommonConfigDocument', []);

        this.callParent(arguments);
    },

    /**
     * @override
     */
    afterRender: function () {
        var formPanel = this.getDetail();
        var originalLoadRecord = formPanel.loadRecord;

        var disableTakeOverButton = this.viisonCommonDisableTakeOverButton.bind(this);
        formPanel.loadRecord = function (record) {
            disableTakeOverButton(record);

            return originalLoadRecord.apply(this, arguments);
        };

        return this.callParent(arguments);
    },

    viisonCommonDisableTakeOverButton: function (record) {
        if (!record) {
            return;
        }

        var takeOverButton = this.down('fieldset[name=elementFieldSet] base-element-button');
        if (takeOverButton === null) {
            // Fallback to the field type used in SW <= 5.6
            takeOverButton = this.down('fieldset[name=elementFieldSet] config-element-button');
        }
        if (takeOverButton === null) {
            return;
        }
        if (this.viisonCommonIsRelevantDocument(record.get('name'))) {
            takeOverButton.setVisible(false);
        } else {
            takeOverButton.setVisible(true);
        }
    },

    viisonCommonIsRelevantDocument: function (documentName) {
        var names = this.viisonRelevantDocumentNames;
        var result = false;
        for (var i = 0; i < names.length; i += 1) {
            result = result || (documentName === names[i]);
        }

        return result;
    },

    /**
     * Add a document type with documentName as name to the documentBoxGuard
     * @param documentName
     */
    viisonAddProtectedDocument: function (documentName) {
        this.viisonRelevantDocumentNames.push(documentName);
    },

});
