// 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.

/**
 * The main controller of the daily closing subapp.
 * It contains only one form having a combobox for the shop selection,
 * two date fields as well as a toolbar with a 'cancel' and a 'submit' button.
 */
//{namespace name="backend/viison_shipping_common_daily_closing/main"}
Ext.define('Shopware.apps.ViisonShippingCommonDailyClosing.view.main.Window', {

    extend: 'Enlight.app.Window',

    alias: 'widget.viison_shipping_common_daily_closing-main_window',

    border: false,

    autoShow: true,

    width: 500,

    height: 350,

    layout: 'border',

    // Default values of plugin-specific settings that can be overridden in plugins
    pluginSupportsDateRange: true,

    snippets: {
        formFields: {
            date: '{s name="window/form_fields/date"}{/s}',
            shop: {
                label: '{s name="window/form_fields/shop/label"}{/s}',
                all: '{s name="window/form_fields/shop/all"}{/s}'
            },
            fromDate: '{s name="window/form_fields/from_date"}{/s}',
            toDate: '{s name="window/form_fields/to_date"}{/s}',
            onlyNewLabels: '{s name="window/form_fields/only_new_labels"}{/s}'
        },
        buttons: {
            cancel: '{s name="window/buttons/cancel"}{/s}',
            showManifest: '{s name="window/buttons/show_manifest"}{/s}'
        },
        loadMaskMsg: '{s name="window/load_mask_msg"}{/s}',
    },

    /**
     * @Override
     */
    initComponent: function() {
        this.title = this.customSnippets.title;
        // Add a description and form
        this.items = [
            {
                region: 'north',
                xtype: 'label',
                html: this.customSnippets.description,
                style: {
                    padding: '5px',
                    whiteSpace: 'normal'
                }
            },
            this.createForm()
        ];

        if (this.pluginSupportsAllShops) {
            this.shopStore.insert(0, [{
                name: this.snippets.formFields.shop.all,
                id: null
            }]);
        }

        // Create a hidden load mask
        this.loadMask = new Ext.LoadMask(this, {
            msg: this.snippets.loadMaskMsg,
        });
        this.loadMask.hide();

        this.callParent(arguments);

        // Setting the fields to disabled on declaration does not work as expected, so disable them after they are rendered
        this.updateDateFieldDisabledState();
    },

    /**
     * Creates and returns a new form containing two fields for the start and end dates
     * as well as a toolbar docked to the bottom of the form.
     *
     * @return The created form.
     */
    createForm: function() {
        var me = this;
        var shopCombobox = Ext.create('Ext.form.field.ComboBox', {
            allowBlank: this.pluginSupportsAllShops,
            fieldLabel: this.snippets.formFields.shop.label,
            name: 'shop',
            store: this.shopStore,
            queryMode: 'local',
            displayField: 'name',
            valueField: 'id'
        });

        if (this.pluginSupportsAllShops) {
            shopCombobox.emptyText = this.snippets.formFields.shop.all;
        } else {
            shopCombobox.setValue((this.shopStore.first()) ? this.shopStore.first().getId() : null);
            shopCombobox.required = false;
        }
        var pluginSupportsTimeSpecification = this.subApp.getController('Main').doesPluginSupportTimeSpecification();
        var dateType = pluginSupportsTimeSpecification ? 'base-element-datetime' : 'datefield';
        var fromDateValue = new Date();
        var toDateValue = new Date();

        if (pluginSupportsTimeSpecification) {
            fromDateValue.setHours(0, 0, 0);
            toDateValue.setHours(0, 0, 0);
            toDateValue.setDate(toDateValue.getDate() + 1);
        }

        var formItems = [shopCombobox];

        if (me.pluginSupportsDateRange) {
            formItems = formItems.concat([{
                xtype: dateType,
                fieldLabel: this.snippets.formFields.fromDate,
                name: 'fromDate',
                value: fromDateValue,
                maxValue: fromDateValue
            }, {
                xtype: dateType,
                fieldLabel: this.snippets.formFields.toDate,
                name: 'toDate',
                value: toDateValue,
                maxValue: toDateValue
            }]);
        } else {
            formItems.push({
                xtype: dateType,
                fieldLabel: this.snippets.formFields.date,
                name: 'date',
                value: fromDateValue,
                maxValue: fromDateValue
            });
        }

        if (this.pluginSupportsOnlyNewLabels) {
            formItems.push({
                xtype: 'checkbox',
                name: 'onlyNewLabels',
                checked: true,
                uncheckedValue: false,
                inputValue: true,
                boxLabel: this.snippets.formFields.onlyNewLabels,
                anchor: '100%',
                listeners: {
                    scope: me,
                    change: me.updateDateFieldDisabledState
                }
            });
        };

        this.form = Ext.create('Ext.form.Panel', {
            region: 'center',
            cls: 'shopware-form',
            layout: 'anchor',
            border: false,
            defaults: {
                margin: '10px',
                anchor: '75%'
            },
            items: formItems,
            dockedItems: [
                this.createToolbar()
            ]
        });

        return this.form;
    },

    /**
     * @return A toolbar containing a secondary 'cancel' button and a primary 'show manifests' button.
     */
    createToolbar: function() {
        var me = this;
        return Ext.create('Ext.toolbar.Toolbar', {
            dock: 'bottom',
            ui: 'shopware-ui',
            cls: 'shopware-toolbar',
            items: [{
                xtype: 'tbfill'
            }, {
                text: this.snippets.buttons.cancel,
                cls: 'secondary',
                action: 'cancel'
            }, {
                text: this.snippets.buttons.showManifest,
                cls: 'primary',
                action: 'showManifest',
                handler: function() {
                    // Fire the event containing the form
                    me.fireEvent('showManifest', me.form.getForm());
                }
            }]
        });
    },

    updateDateFieldDisabledState: function() {
        if (this.pluginSupportsOnlyNewLabels) {
            var me = this;
            var disabled = me.down('[name="onlyNewLabels"]').checked;
            me.down('[name="fromDate"]').setDisabled(disabled);
            me.down('[name="toDate"]').setDisabled(disabled);
        }
    }

});
