/*
 *  Copyright 2025 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.
 */

/**
 * Define the form entries expiration
 */
Ext.define('Ametys.plugins.forms.actions.FormEntriesExpirationPolicyAction', {
    singleton: true,
    
    /**
     * Opens a dialog to configure the form expiration
     * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling this function
     */
    act: function(controller)
    {
        var targets = controller.getMatchingTargets();
        if (!targets.length == 1)
        {
            return;
        }
        
        this._formId = targets[0].getParameters().id;
		this._delayedInitialize(controller);
        this._initForm();
    },
    
    /**
     * @private
     */
    _delayedInitialize: function ()
    {
        if (this._initialized)
        {
            return;
        }
        
		var me = this;
		this._form = Ext.create('Ext.form.Panel', {
			border: false,
			layout: 'anchor',
			defaults:{
				labelAlign: 'top',
				anchor: '100%',
                labelSeparator: ''
			},
			
			items: [ 
				{
					name: 'expirationEnabled',
					xtype: 'checkboxfield',
					inputValue: true,
					uncheckedValue: false,
					checked: false,
		        	boxLabel: "{{i18n PLUGINS_FORMS_EXPIRATION_ENABLED_FORM_PROPERTY_LABEL}}",
					listeners: {
						'change': (checkbox, value) => {
							me._form.getForm().findField('expirationPeriod').setDisabled(!value);
							me._form.getForm().findField('expirationPolicy').setDisabled(!value);
						}
					}
		        },
				{
					name: 'expirationPeriod',
					xtype: 'numberfield',
					allowBlank: false,
					minValue: 1,
					defaultValue: 1,
		        	fieldLabel: "{{i18n PLUGINS_FORMS_EXPIRATION_PERIOD_FORM_PROPERTY_LABEL}} *",
			        ametysDescription: "{{i18n PLUGINS_FORMS_EXPIRATION_PERIOD_FORM_PROPERTY_DESC}}",
					disabled: true,
					margin: '0 0 0 20'
		        },
		        {
		        	name: 'expirationPolicy',
		        	xtype: 'combobox',
		        	fieldLabel: "{{i18n PLUGINS_FORMS_EXPIRATION_ACTION_FORM_PROPERTY_LABEL}} *",
			        ametysDescription: "{{i18n PLUGINS_FORMS_EXPIRATION_ACTION_FORM_PROPERTY_DESC}}",
					valueField: 'value',
					store: Ext.create('Ext.data.Store', {
					      fields: ['value', 'text'],
					      sorters: 'text',
					      data: [
					          { value: 'DELETE',   text: "{{i18n PLUGINS_FORMS_EXPIRATION_ACTION_DELETE_LABEL}}"},
					          { value: 'ANONYMIZE',  text: "{{i18n PLUGINS_FORMS_EXPIRATION_ACTION_ANONYMIZE_LABEL}}"}
					      ]
				    }),
					editable: false,
					forceSelection: true,
					defaultValue: 'DELETE',
					allowBlank: false,
					disabled: true,
					margin: '0 0 0 20'
		        }
			]
		});
        
        this._box = Ext.create('Ametys.window.DialogBox',  {
            
            title : "{{i18n PLUGINS_FORMS_SET_ENTRIES_EXPIRATION_DIALOG_TITLE}}",
            iconCls : "ametysicon-time33",
            
            width: 450,
            layout: 'anchor',

            items : [{
                        xtype: 'container',
                        cls: 'a-text',
                        html: "{{i18n PLUGINS_FORMS_SET_ENTRIES_EXPIRATION_DIALOG_HINT}}",
                      },
                      this._form 
            ],
            
            closeAction: 'hide',
            
            referenceHolder: true,
            defaultButton: 'validate',
            
            buttons : [{
                reference: 'validate',
                text: "{{i18n PLUGINS_FORMS_SET_ENTRIES_EXPIRATION_OK_BTN}}",
                handler: Ext.bind(this._ok, this)
            }, {
                text: "{{i18n PLUGINS_FORMS_SET_ENTRIES_EXPIRATION_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.dao.FormDAO",
            methodName: "getFormExpiration",
            parameters: [this._formId],
            callback: {
                handler: this._initFormCb,
                scope: this
            },
            waitMessage: true,
			errorMessage: true
        });
    },
    
    /**
     * @private
     * Callback for the form initialization process
     * @param {Object} response the expiration data
     */
    _initFormCb: function(response)
    {
		var form = this._form.getForm();
		form.clearInvalid();
		form.reset();
		
		var expirationEnabled = response.expirationEnabled;
		form.findField('expirationEnabled').setValue(expirationEnabled);
		
		var expirationPeriod = response.expirationPeriod;
		if (expirationPeriod > 0)
		{
			form.findField('expirationPeriod').setValue(expirationPeriod);
		}
        form.findField('expirationPolicy').setValue(response.expirationPolicy);
		
		form.findField('expirationPeriod').setDisabled(expirationEnabled !== true);
		form.findField('expirationPolicy').setDisabled(expirationEnabled !== true);
				
        this._box.show();
    },
    
    /**
     * @private
     * Saving process
     */
    _ok: function ()
    {
        var form = this._form.getForm();
        if (!form.isValid())
        {
            return;
        }
		
		var values = form.getValues();
		
		if (values.expirationEnabled)
		{
			Ametys.data.ServerComm.callMethod({
	            role: "org.ametys.plugins.forms.dao.FormDAO",
	            methodName: "setExpirationPolicy",
	            parameters: [this._formId, Number(values.expirationPeriod), values.expirationPolicy],
	            callback: {
	                handler: this._setFormExpirationCb,
	                scope: this
	            },
	            waitMessage: true,
				errorMessage: true
	        });
		}
		else
		{
			Ametys.data.ServerComm.callMethod({
	            role: "org.ametys.plugins.forms.dao.FormDAO",
	            methodName: "removeExpirationPolicy",
	            parameters: [this._formId],
	            callback: {
	                handler: this._setFormExpirationCb,
	                scope: this
	            },
	            waitMessage: true,
				errorMessage: true
	        });
		}
    },
    
    /**
     * @private
     */
    _setFormExpirationCb: function (response)
    {
		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
     */
    _cancel: function ()
    {
        this._box.hide();
    }
});