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

/**
 * This UI helper provides a dialog box to create a new content type
 */
Ext.define('Ametys.plugins.contenttypeseditor.editor.EditContentTypeHelper',  {
    singleton: true,
    
    /**
     * @private
     * @property {Function} _cbFn The callback function invoked when a new content type is created
     */
    
    /**
     * @property {Ametys.window.DialogBox} _box The dialog box for creating/editing a content type.
     * @private
     */
    
    /**
     * @property {Ext.form.Panel} _form The panel containing forms.
     * @private
     */
    
    /**
     * @property {String} _mode The current edition mode ('new' or 'edit')
     * @private
     */
    
    /**
     * Configure and open the dialog box
     * @param {Object} config The configuration options:
     * @param {String} config.title The title of dialog box
     * @param {String} config.iconCls The CSS class for the icon of the dialog box
     * @param {String} config.helpMessage The help message to display on top of dialog box
     * @param {Function} config.callback The callback function invoked when a new content type is created. The callback function will received the following parameters:
     * @param {Object} config.callback.contentTypeInfos All information about a content type 
     */
    add: function(config)
    {
        this._mode = 'new';
        this._cbFn = config.callback;
        this._createDialogBox(config.title, config.iconCls, config.helpMessage);
        this._displayAddFields();
        this._initializeGlyph();
        this._box.show();
    },
    
    /**
     * Configure and open the dialog box
     * @param {Object} config The configuration options:
     * @param {String} config.title The title of dialog box
     * @param {String} config.iconCls The CSS class for the icon of the dialog box
     * @param {String} config.helpMessage The help message to display on top of dialog box
     * @param {Object} config.contentTypeInfo All information about a content type
     * @param {Function} config.callback The callback function invoked when a new content type is created. The callback function will received the following parameters:
     * @param {Object} config.callback.contentTypeInfos All new information about a content type 
     */
    edit: function(config)
    {
        this._mode = 'edit';
        this._cbFn = config.callback;
        this._contentTypeInfo = config.contentTypeInfo;
        this._createDialogBox(config.title, config.iconCls, config.helpMessage);
        this._fillFields(config.contentTypeInfo);
        this._displayEditFields();
        this._box.show();
        this._iconWarning();
    },
    
    /**
     * @private
     * Create the dialog to add a new content type
     * @param {String} title The title of the dialog box.
     * @param {String} iconCls The CSS class for the icon of the dialog box.
     * @param {String} helpMessage The help message to display on top of dialog box.
     */
    _createDialogBox: function(title, iconCls, helpMessage)
    {
        this._form = this._createFormPanel(helpMessage);
        
        this._box = Ext.create('Ametys.window.DialogBox', {
            title: title || "",
            width: 600,
            layout: 'fit',
            scrollable: true,
            iconCls: iconCls || 'ametysicon-add64',
            referenceHolder: true,
            
            items: [this._form],
            
            closeAction: 'destroy'
        });
    },
    
    /**
     * @private
     * Create the main panel of the dialog box
     * @param {String} [helpMessage] The optionnal introduction message
     * @return {Ext.form.Panel} The form panel with all the fields to edit
     */
    _createFormPanel: function(helpMessage)
    {
        var formPanel = Ext.create('Ext.form.Panel', {
            defaults: {
                cls: 'ametys',
                labelSeparator: '',
                labelStyle: 'font-weight: bold',
                labelWidth: 150,
                width: '100%',
                msgTarget: 'side'
            },
            items: [
                {
                    xtype: "component",
                    cls: "a-text",
                    html: helpMessage || ""
                },
                {
                    xtype: "textfield",
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_ID_INPUT_LABEL}} *",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_ID_INPUT_DESCRIPTION}}",
                    allowBlank: false,
                    name: 'content-type-id',
                    id: 'content-type-id',
                    regex: /^[A-Za-z0-9].*$/,
                    regexText: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_ID_INPUT_INVALID}}"
                },
                {
                    xtype: "combobox",
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_PLUGIN_INPUT_LABEL}} *",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_PLUGIN_INPUT_DESCRIPTION}}",
                    name: 'content-type-plugin',
                    id: 'content-type-plugin',
                    valueField: 'id',
                    displayField: 'label',
                    allowBlank: false,
                    editable: true,
                    forceSelection: true,
                    queryMode: 'local',
                    store: {
                        autoLoad: true,
                        proxy: {
                            type: 'ametys',
                            role: 'org.ametys.plugins.contenttypeseditor.edition.EditContentTypeInformationHelper',
                            methodName: 'getPluginNames',
                            methodArguments: []
                        },
                        sorters: [{property: 'label', direction: 'ASC'}],
                        fields: [
                            {name: 'id'},
                            {name: 'label', type: 'string'}
                        ],
                        listeners: {
                            'load' : this._onStoreLoad,
                            scope: this
                        }
                    }
                },
                {
                    xtype: "edition.select-content-types",
                    multiple: "true",
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_SUPERTYPES_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_SUPERTYPES_INPUT_DESCRIPTION}}",
                    name: 'content-type-supertypes',
                    id: 'content-type-supertypes'
                },
                {
                    xtype: "enhancedmultilingualstring",
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_LABEL_INPUT_LABEL}} *",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_LABEL_INPUT_DESCRIPTION}}",
                    allowBlank: false,
                    name: 'content-type-label',
                    id: 'content-type-label'
                },
                {
                    xtype: "enhancedmultilingualstring",
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_DEFAULT_TITLE_INPUT_LABEL}} *",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_DEFAULT_TITLE_INPUT_DESCRIPTION}}",
                    allowBlank: false,
                    name: 'content-type-default-title',
                    id: 'content-type-default-title'
                },
                {
                    xtype: "enhancedmultilingualstring",
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_DESCRIPTION_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_DESCRIPTION_INPUT_DESCRIPTION}}",
                    name: 'content-type-description',
                    id: 'content-type-description'
                },
                {
                    xtype: "combobox",
                    name: 'content-type-category',
                    id: 'content-type-category',
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_CATEGORY_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_CATEGORY_INPUT_DESCRIPTION}}",
                    valueField: 'value',
                    displayField: 'value',
                    editable: true,
                    forceSelection: true,
                    allowBlank: true,
                    queryMode: 'local',
                    listeners:{
                         'select': this._onCategorySelected,
                         scope: this
                    },
                    store: {
                        model: 'Ametys.plugins.contenttypeseditor.editor.editcontenttypehelper.Category',
                        autoLoad: true,
                        proxy: {
                            type: 'ametys',
                            role: 'org.ametys.plugins.contenttypeseditor.edition.EditContentTypeInformationHelper',
                            methodName: 'getCategories',
                            methodArguments: []
                        }
                    }
                },
                {
                    xtype: 'enhancedmultilingualstring',
                    id: 'content-type-new-category',
                    name: 'content-type-new-category',
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_NEW_CATEGORY_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_NEW_CATEGORY_INPUT_DESCRIPTION}}",
                    disabled: true
                },
                {
                    xtype: 'edition.illustration',
                    defaultSources: [],
                    glyphSources: [Ametys.form.widget.Illustration.ApplicationGlyph.SOURCE],
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_GLYPH_INPUT_LABEL}} *",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_GLYPH_INPUT_DESCRIPTION}}",
                    allowBlank: false,
                    name: 'content-type-icon-glyph',
                    id: 'content-type-icon-glyph'
                },
                {
                    xtype: "fieldcontainer",
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_TAG_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_TAG_INPUT_DESCRIPTION}}",
                    name: 'content-type-tag',
                    id: 'content-type-tag',
                    layout: 'vbox',
                    defaults: {
		                anchor: '100%'
		            },
                    items: [
		                {
                            xtype: 'checkboxfield',
		                    boxLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_TAG_INPUT_PRIVATE}}",
		                    id: 'content-type-tag-private',
                            name: 'content-type-tag-private'
		                },
                        {
				            xtype: 'splitter'
				        },
                        {
                            xtype: 'checkboxfield',
		                    boxLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_TAG_INPUT_REFERENCE_TABLE}}",
		                    id: 'content-type-tag-reference-table',
                            name: 'content-type-tag-reference-table'
		                },
                        {
				            xtype: 'splitter'
				        },
                        {
                            xtype: 'checkboxfield',
		                    boxLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_TAG_INPUT_MIXIN}}",
		                    id: 'content-type-tag-mixin',
                            name: 'content-type-tag-mixin'
		                },
                        {
                            xtype: 'splitter'
                        },
                        {
                            xtype: 'checkboxfield',
                            boxLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_TAG_INPUT_ABSTRACT}}",
                            id: 'content-type-abstract',
                            name: 'content-type-abstract'
                        }
		            ]
                },
                {
                    xtype: 'textfield',
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_OTHER_TAG_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_OTHER_TAGS_INPUT_DESCRIPTION}}",
                    id: 'content-type-tags',
                    name: 'content-type-tags',
                    regex: /^[\w-]+(\s[\w-]+)*(,[\w-]+(\s[\w-]+)*)*$/,
                    regexText: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_TAG_INPUT_INVALID}}"
                },
                {
                    xtype: 'edition.multilingual-string',
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_RIGHT_INPUT_LABEL}} *",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_RIGHT_INPUT_DESCRIPTION}}",
                    allowBlank: false,
                    id: 'content-type-right',
                    name: 'content-type-right'
                },
                {
                    xtype: 'combobox',
                    fieldLabel: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_PARENT_REFERENCE_INPUT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CONTENT_TYPE_PARENT_REFERENCE_INPUT_DESCRIPTION}}",
                    allowBlank: true,
                    id: 'content-type-parent-reference',
                    name: 'content-type-parent-reference',
                    valueField: 'name',
                    displayField: 'name',
                    editable: true,
                    forceSelection: true,
                    queryMode: 'local',
                    disabled: true,
                    store: 
                    {
                        autoLoad: true,
                        sorters: [{property: 'name', direction: 'ASC'}],
                        fields: ['name'],
                        listeners:
                        {
                            'beforeload' : this._onBeforeLoadParentRef,
                            scope: this
                        }
                    }
                }
            ],
            
            buttons:
                [
                    {
                        formBind: true, //only enabled once the form is valid
                        text: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_OK_BUTTON}}",
                        handler: this._verify,
                        scope: this
                    },
                    {
                        text: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_CANCEL_BUTTON}}",
                        handler: this._cancel,
                        scope: this
                    }
                ]
            
        });
        
        return formPanel;
    },
    
    /**
     * @private
     * Listener when the select to choose content type has changed
     * @param {Ext.form.field.ComboBox} combo The select of content types
     * @param {Ext.data.Model} record The record selected
     */
    _onCategorySelected: function(combo, record)
    {
        if (record.data.isNew)
        {
            this._form.getForm().findField("content-type-new-category").enable();
        }
        else
        {
            this._form.getForm().findField("content-type-new-category").disable();
        }
    },
    
    /**
     * @private
     * Fires whenever the store reads data from a remote data source.
     * This method set the value by default for the content type plugin.
     * @param {Ext.data.Store} store The store
     * @param {Ext.data.Model[]} records An array of records
     */
    _onStoreLoad: function(store, records) {
        if (this._mode == 'new')
        {
	        var defaultValue = records[0].data.id;
	        var pluginValues = [];
	        Ext.Array.each(records, function(record) {
	            pluginValues.push(record.data.id);
	        });
	        if (Ext.Array.contains(pluginValues, "web"))
	        {
	            defaultValue = "web";
	        }
	        else if ((Ext.Array.contains(pluginValues, "cms")))
	        {
	            defaultValue = "cms";
	        }
	        this._form.getForm().findField("content-type-plugin").setValue(defaultValue);
        }
    },
    
    /**
     * @private
     * Fires before a request is made for a new data object.
     * This method load parent references.
     * @param {Ext.data.Store} store The store
     */
    _onBeforeLoadParentRef: function(store)
    {
        if (this._mode == 'edit')
        {
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.contenttypeseditor.edition.EditContentTypeInformationHelper",
                methodName: "getParentReferenceAttributes",
                parameters: [this._contentTypeInfo.id, this._contentTypeInfo.superTypes, this._contentTypeInfo.metadata],
                callback: {
                    handler: this._loadParentRef,
                    arguments: {
                        store: store
                    },
                    scope: this
                }
            }); 
        }
    },
    
    /**
     * @private
     * Server response to get parent ref metadata
     * @param {Object[]} metadata The names of the parent metadatas. The object have a 'name'. 
     * @param {Object} args The 'store' value contains the parent metadata store
     */
    _loadParentRef: function(metadata, args)
    {
        if (metadata.length > 0)
        {
            args.store.setData(metadata);
            this._form.getForm().findField("content-type-parent-reference").setValue(this._contentTypeInfo.parentRef);
        }
    },
    
    /**
     * @private
     * Initialize the glypht of the content type with the given value
     * @param {String} [contentTypeGlyph] The css class for the glyphe
     */
    _initializeGlyph: function(contentTypeGlyph)
    {
        var glyph = {};
        this._form.getForm().findField("content-type-icon-glyph").setValue(glyph);
        if (contentTypeGlyph)
        {
            glyph.type = 'glyph';
            glyph.id = contentTypeGlyph;
            this._form.getForm().findField("content-type-icon-glyph").setValue(glyph);
        }
    },
    
    /**
     * @private
     * When opening an existing content type, will fill all the fields with the informations on the content type
     * @param {Object} contentTypeInfo The object given as a config of the #edit method
     */
    _fillFields: function(contentTypeInfo)
    {
       this._form.getForm().findField("content-type-id").setValue(contentTypeInfo.id); 
       this._form.getForm().findField("content-type-plugin").setValue(contentTypeInfo.plugin);
       this._form.getForm().findField("content-type-supertypes").setValue(contentTypeInfo.superTypes);
       this._form.getForm().findField("content-type-tag-private").setValue(contentTypeInfo.private);
       this._form.getForm().findField("content-type-tag-mixin").setValue(contentTypeInfo.mixin);
       this._form.getForm().findField("content-type-tag-reference-table").setValue(contentTypeInfo.referenceTable);
       this._form.getForm().findField("content-type-abstract").setValue(contentTypeInfo.abstract);
       this._initializeGlyph(contentTypeInfo.glyph);
       this._form.getForm().findField("content-type-label").setValue(contentTypeInfo.label);
       this._form.getForm().findField("content-type-default-title").setValue(contentTypeInfo.defaultTitle);
       this._form.getForm().findField("content-type-description").setValue(contentTypeInfo.description);
       this._form.getForm().findField("content-type-right").setValue(contentTypeInfo.right);
       this._form.getForm().findField("content-type-tags").setValue(contentTypeInfo.tags);
       
       if (!Ext.Object.isEmpty(contentTypeInfo.category))
       {
            var category = contentTypeInfo.category;
            var language = Ametys.cms.language.LanguageDAO.getCurrentLanguage();
            var result = "";
            if (category.isMultilingual)
            {
                result = category.values[language];
            }
            else
            {
                result = category.values;
            }
            this._form.getForm().findField("content-type-category").setValue(result);
       }
       if (!Ext.Object.isEmpty(contentTypeInfo.newCategory))
       {
            this._form.getForm().findField("content-type-new-category").setValue(contentTypeInfo.newCategory);
            this._form.getForm().findField("content-type-new-category").enable();
       }
    },
    
    /**
     * @private
     * Enable/disable the fields used during the edition of an existing content type
     */
    _displayEditFields: function()
    {
        this._form.getForm().findField("content-type-id").disable();
        this._form.getForm().findField("content-type-plugin").disable();
        this._form.getForm().findField("content-type-supertypes").disable();
        this._form.getForm().findField("content-type-tag-private").disable();
        this._form.getForm().findField("content-type-tag-reference-table").disable();
        this._form.getForm().findField("content-type-tag-mixin").disable();
        this._form.getForm().findField("content-type-abstract").disable();
        this._form.getForm().findField("content-type-tags").disable();
        this._form.getForm().findField("content-type-right").disable();
        this._form.getForm().findField("content-type-parent-reference").enable();
    },
    
    /**
     * @private
     * Enable/disable the fields used during the creation of a new content type
     */
    _displayAddFields: function()
    {
        this._form.getForm().findField("content-type-id").enable();
        this._form.getForm().findField("content-type-plugin").enable();
        this._form.getForm().findField("content-type-supertypes").enable();
        this._form.getForm().findField("content-type-tag-private").enable();
        this._form.getForm().findField("content-type-tag-reference-table").enable();
        this._form.getForm().findField("content-type-tag-mixin").enable();
        this._form.getForm().findField("content-type-abstract").enable();
        this._form.getForm().findField("content-type-tags").enable();
        this._form.getForm().findField("content-type-right").enable();
        this._form.getForm().findField("content-type-parent-reference").disable();
    },
    
    /**
     * @private
     * Displays a warning if the existing content type was using images... since we only support glyphs in edition
     */
    _iconWarning: function()
    {
        if (this._contentTypeInfo.hasImages && !this._contentTypeInfo.glyph)
        {
            Ext.Msg.show({
                title: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ICON_INCOMPATIBLE_TITLE}}",
                message: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ICON_INCOMPATIBLE_MESSAGE}}",
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.WARNING
            }); 
        }
    },
    
    /**
     * @private
     * This method verify, if there are supertypes, if the are compatible by calling server. 
     */
    _verify: function()
    {
        if (this._mode == 'new')
        {
            var superTypeIds = this._form.getForm().findField("content-type-supertypes").getValue();
	        if (superTypeIds.length > 0)
	        {
	            Ametys.data.ServerComm.callMethod({
	                role: "org.ametys.plugins.contenttypeseditor.edition.EditContentTypeInformationHelper",
	                methodName: "areContentTypesCompatible",
	                parameters: [superTypeIds],
	                callback: {
	                    handler: this._verifyCb,
	                    scope: this
	                }
	            });
	        }
	        else
	        {
	            this._validate();
	        }
        }
        else
        {
            this._validate();
        }
        
    },
    
    /**
     * This method display a message error if supertypes of content type are not compatible or validate if there are compatible.
     * @param {Boolean} success True if supertypes are compatible, false if not.
     */
    _verifyCb: function(success)
    {
        if (success)
        {
            this._validate();
        }
        else
        {
           Ametys.Msg.show({
                title: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_INCOMPATIBLE_SUPERTYPES_TITLE}}",
                msg: "{{i18n PLUGINS_CONTENTTYPESEDITOR_ADD_CONTENT_TYPE_DIALOG_INCOMPATIBLE_SUPERTYPES_MESSAGE}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            }); 
        }
    },
    
    /**
     * @private
     * This method send all information about a content type to the callback.
     */
    _validate: function()
    {
        if (Ext.isFunction(this._cbFn))
        {
            var form = this._form.getForm();
            
            var contentTypeInfos = {
                pluginName: form.findField("content-type-plugin").getValue(),
                id: form.findField("content-type-id").getValue(),
                label: form.findField("content-type-label").getValue(),
                defaultTitle: form.findField("content-type-default-title").getValue(),
                description: form.findField("content-type-description").getValue(),
                iconGlyph: form.findField("content-type-icon-glyph").getValue().id,
                private: form.findField("content-type-tag-private").getValue(),
                referencetable: form.findField("content-type-tag-reference-table").getValue(),
                mixin: form.findField("content-type-tag-mixin").getValue(),
                abstract: form.findField("content-type-abstract").getValue(),
                tags: form.findField("content-type-tags").getValue(),
                right: form.findField("content-type-right").getValue(),
                parentRef: form.findField("content-type-parent-reference").getValue()
            };
            
            var category = form.findField("content-type-category").lastSelection;
            if (category && category.length > 0)
            {
                contentTypeInfos.category = form.findField("content-type-category").lastSelection[0].data;
                if (contentTypeInfos.category.isNew)
                {
                    contentTypeInfos.newCategory = form.findField("content-type-new-category").getValue();
                }
            }
            var superTypeIds = form.findField("content-type-supertypes").getValue();
            var widgetStore = form.findField("content-type-supertypes").getStore();
            if (superTypeIds.length > 0)
            {
                contentTypeInfos.superTypes = [];
                for (var i = 0; i < superTypeIds.length; i ++)
                {
                    var superTypeId = superTypeIds[i];
                    contentTypeInfos.superTypes.push({
                        id: superTypeId,
                        label: widgetStore.getById(superTypeId).data.label
                    });
                }
            }
            this._cbFn(contentTypeInfos);
        }
        this._box.close();
    },
    
    /**
     * @private
     * Listener when closing the dialog box
     */
    _cancel: function()
    {
        this._box.close();
    }
    
});

/**
 * This class is the model for entries in a combobox of all existing categories of a content type
 * @private
 */
Ext.define('Ametys.plugins.contenttypeseditor.editor.editcontenttypehelper.Category', { 
    extend: 'Ext.data.Model',
    
    fields: [
         'isMultilingual',
         'values',
         'isNew',
         'key',
         'catalogue',
         {
            name: 'value',
            depends: ['isMultilingual', 'values'],
            calculate: function (data)
            {
                var value = "";
                if (data.isMultilingual)
                {
                    var language = Ametys.cms.language.LanguageDAO.getCurrentLanguage();
                    value = data.values[language];
                }
                else
                {
                    value = data.values;  
                }
                return value;
            }
        }
    ]
});