/*
 *  Copyright 2022 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Schedule the scheduled of form
 */
Ext.define(
    'Ametys.plugins.forms.actions.ScheduleOpeningAction', 
    {
        singleton: true,
        
        /**
         * @private
         * @property {Ametys.window.DialogBox} _box The dialog box
         */
    
        /**
         * @private
         * @property {Ext.form.Basic} _formPanel the form panel
         */
         
         /**
         * @private
         * @property {String} _box The box
         */
        
        /**
         * @private
         * @property {Boolean} _initialized Is the dialog box initialized ?
         */
        
        /**
         * Schedule the scheduled of a form
         * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling this function
         */
        act: function(controller)
        {
            var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
            if (!target)
            {
                return;
            }
            
            this._formId = target.getParameters().id;
            this._delayedInitialize(controller);
            
            // Init form with the first selection
            this._initForm();
            this._box.show();
        },
    
        /**
         * Initialize the form with values provided by the server
         */
        _delayedInitialize: function ()
        {
            if (this._initialized)
            {
                return;
            }
            
            this._formPanel = Ext.create('Ext.form.Panel', {
                labelWidth: 120,
                border: false,
                
                defaultType :'datefield',
                
                defaults: {
                    cls: 'ametys',
                    labelWidth: 100,
                    labelAlign: 'right',
                    labelSeparator: '',
                    msgTarget: 'side'
                },
                
                scrollable: true,
                
                items: [ 
                        {
                            name: 'startDate',
                            itemId: 'startDate',
                            fieldLabel: "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_START_DATE}}",
                            ametysDescription: "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_START_DATE_DESC}}"
                        },
                        {
                            name: 'endDate',
                            itemId: 'endDate',
                            fieldLabel: "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_END_DATE}}",
                            ametysDescription: "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_END_DATE_DESC}}"
                        }
                ]
            });
    
            this._box = Ext.create('Ametys.window.DialogBox',  {
                
                title : "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_DIALOG_TITLE}}",
                iconCls : "ametysicon-time33",
                
                width: 430,
                layout: 'form',
    
                items : [{
                            xtype: 'container',
                            cls: 'a-text',
                            html: "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_HINT}}",
                          },
                          this._formPanel 
                ],
                
                defaultFocus: 'startDate',
                closeAction: 'hide',
                
                referenceHolder: true,
                defaultButton: 'validate',
                
                buttons : [{
                    reference: 'validate',
                    text: "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_DIALOG_OK_BTN}}",
                    handler: Ext.bind(this._ok, this)
                }, {
                    text: "{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_DIALOG_CANCEL_BTN}}",
                    handler: Ext.bind(this._cancel, this)
                } ]
            });
            
            this._initialized = true;
        },
    
        /**
         * @private
         * Initialize the form with values provided by the server
         */
        _initForm: function ()
        {
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.forms.helper.ScheduleOpeningHelper",
                methodName: "getScheduledDates",
                parameters: [this._formId],
                callback: {
                    handler: this._initFormCb,
                    scope: this
                },
                waitMessage: true,
				errorMessage: true
            });
        },
        
        /**
         * @private
         * Callback for the form initialization process
         * @param {Object} response the server's response
         * @param {String} [response.startDate] the scheduled starting date
         * @param {String} [response.endDate] the scheduled ending date
         */
        _initFormCb: function(response)
        {
            var startDate = response.startDate;
            var endDate = response.endDate;
    
            var form = this._formPanel.getForm();
            form.findField('startDate').setValue(!Ext.isEmpty(startDate) ? Ext.Date.parse(startDate, Ext.Date.patterns.ISO8601DateTime) : '');
            form.findField('endDate').setValue(!Ext.isEmpty(endDate) ? Ext.Date.parse(endDate, Ext.Date.patterns.ISO8601DateTime) : '');
            
            form.clearInvalid();
        },
    
        /**
         * @private
         * Saving process
         */
        _ok: function ()
        {
            var form = this._formPanel.getForm();
            if (!form.isValid())
            {
                return;
            }
            
            var startDate = form.findField('startDate').getValue();
            var endDate = form.findField('endDate').getValue();
            
            // Check date consistency
            if (!Ext.isEmpty(endDate) && !Ext.isEmpty(startDate) && endDate.getTime() - startDate.getTime() <= 0)
            {
                form.findField('endDate').markInvalid ("{{i18n PLUGINS_FORMS_OPENING_SCHEDULE_INTERVAL_ERROR}}");
                return;
            }
            
            var startDate = !Ext.isEmpty(startDate) ? Ext.Date.format(startDate, Ext.Date.patterns.ISO8601Date) : null;
            var endDate = !Ext.isEmpty(endDate) ? Ext.Date.format(endDate, Ext.Date.patterns.ISO8601Date) : null;
            
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.forms.helper.ScheduleOpeningHelper",
                methodName: "setScheduledDate",
                parameters: [this._formId, startDate, endDate],
                callback: {
                    handler: this._setScheduledDateCb,
                    scope: this
                },
                waitMessage: true,
				errorMessage: true
            });
        },
    
        /**
         * @private
         * Callback function after setting scheduled dates
         */
        _setScheduledDateCb: function ()
        {
            this._box.hide();
            
            var targets = [{
                id: Ametys.message.MessageTarget.FORM_TARGET,
                parameters: {
                    id: this._formId
                }
            }];
            
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.MODIFIED,
                parameters: {major: false},
                targets: targets
            });
        },
        
        /**
         * @private
         * Handler invoked when the box's 'Cancel' button is clicked. Hides the box.
         */
        _cancel: function ()
        {
            this._box.hide();
        }
    }
);