/*
 *  Copyright 2015 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 step of {@link Ametys.plugins.web.page.AddPageWizard} wizard allow to define page's title.
 */
Ext.define("Ametys.plugins.web.page.AddPageWizard.CreatePageCard", {
	
	extend: "Ametys.plugins.web.page.AddPageWizard.Card",
	
	/**
	 * @private
	 * @property {Object} _model The card model
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		this._model = {};
	},
		
	/**
	 * Creates the card panel
	 * @return {Ext.Component} the created card panel
	 */
	createPanel: function ()
	{
        var cardPanelItems = [];
        var parentPages = Ametys.plugins.web.page.AddPageWizard.getParentPages();
        if (Array.isArray(parentPages) && parentPages.length > 1)
        {
            var parentPageSelector = [{
                xtype:'container',
                cls: 'a-text',
                html: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['parent-help']
            },
            {
                xtype: 'combo',
                itemId: 'parent-page-combo',
                name: 'parent-page-combo',
                fieldLabel : Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['page-title-label'],
                allowBlank: false,
                editable: false,
                store: parentPages,
                queryMode: 'local',
                displayField: 'title',
                valueField: 'id',
                listeners: {
                    'select': function(combo, record, eOpts)
                    {
                        Ametys.plugins.web.page.AddPageWizard._initRights(record.data);
                        Ametys.plugins.web.page.AddPageWizard._onChange();
                    }
                }
            }];
            
            cardPanelItems = cardPanelItems.concat(parentPageSelector);
        }
        
        var defaultItems = [
                    {
                        xtype:'container',
                        cls: 'a-text',
                        itemId: 'add-page-title-help',
                        html: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['title-help']
                    },
                    {
                        itemId: 'add-page-title',
                        name: 'add-page-title',
                        fieldLabel : Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['page-title'],
                        allowBlank: false,
                        
                        regex: /[a-z]/i,
                        regexText: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['page-title-regex-message'],
                        
                        enableKeyEvents: true,
                        listeners: {
                            'change': Ext.bind(Ametys.plugins.web.page.AddPageWizard._onChange, Ametys.plugins.web.page.AddPageWizard),
                            'keyup': Ext.bind(Ametys.plugins.web.page.AddPageWizard._onChange, Ametys.plugins.web.page.AddPageWizard)
                        }
                    },
                    {
                        xtype:'container',
                        cls: 'a-text',
                        itemId: 'add-page-title-hint1',
                        html: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['hint']
                    },
                    {
                        xtype: 'textfield',
                        
                        itemId: 'add-page-title-long',
                        name: 'add-page-title-long',
                        fieldLabel : Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['page-long-title'],
                        
                        allowBlank: true,
                        
                        enableKeyEvents: true,
                        listeners: {
                            'change': Ext.bind(Ametys.plugins.web.page.AddPageWizard._onChange, Ametys.plugins.web.page.AddPageWizard),
                            'keyup': Ext.bind(Ametys.plugins.web.page.AddPageWizard._onChange, Ametys.plugins.web.page.AddPageWizard)
                        }
                    },
                    {
                        xtype:'container',
                        cls: 'a-text',
                        itemId: 'add-page-title-hint2',
                        html: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['hint2']
                    }
            ];
        cardPanelItems = cardPanelItems.concat(defaultItems);
        
		this._cardPanel = Ext.create ('Ext.Container',  {
			border: false,
			scrollable: true,
            layout: 'anchor',
		    
		    defaults: {
		    	xtype: 'textfield',
		    	cls: 'ametys',
        		msgTarget: 'side',
        		labelAlign: 'top',
        		labelSeparator: '',
        		labelStyle: 'font-weight: bold',
        		labelWidth: 130,
        		maxWidth: 470,
                width: '100%'
		    },
		    
	        items: cardPanelItems
	    });
		
		return this._cardPanel;
	},
	
	apply: function (fullModel, callback)
	{
		// Create page
		var parentId = Ametys.plugins.web.page.AddPageWizard.getParentId();
		Ametys.web.page.PageDAO.createPage([parentId, fullModel['title'], fullModel['title-long']], this._applyCb, {scope: this, arguments: {fullModel: fullModel, callback: callback}, waitMessage: {msg: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['page']['wait-message'], target: this.getUI().ownerCt}});
	},
	
	/**
	 * @private
	 * Callback function called after creating page
	 * @param {Object} response The server result
	 * @param {Object} response.id The id of created page
	 * @param {Object} response.parentId The id of parent page or sitemap
	 * @param {Object} args The callback arguments
	 */
	_applyCb: function (response, args)
	{
		Ametys.web.page.PageDAO.getPage (response.id, Ext.bind(this._applyCb2, this, [args.fullModel, args.callback], true));
	},
	
	/**
	 * @private
	 * Callback function invoked after getting created page
	 * @param {Ametys.web.page.Page} page The created page
	 * @param {Object} fullModel The full model
	 * @param {Function} callback The callback function
	 */
	_applyCb2: function (page, fullModel, callback)
	{
		fullModel['page'] = page;
		fullModel['page-id'] = page.getId();
		fullModel['page-lang'] = page.getLang();
		
		callback(true);
	},
	
	getUI: function ()
	{
		return this._cardPanel;
	},
	
	updateUI: function(callback)
	{
		this._cardPanel.queryById("add-page-title").setValue(this._model["title"]);
		this._cardPanel.queryById("add-page-title-long").setValue(this._model["title-long"]);
        this._cardPanel.queryById("add-page-title-long").setVisible(Ametys.plugins.web.page.AddPageWizard.getInitialConfig('show-page-long-title'));
        this._cardPanel.queryById("add-page-title-hint1").setVisible(Ametys.plugins.web.page.AddPageWizard.getInitialConfig('show-page-long-title'));
        
        callback(true);
	},

    isModelOk: function(fullModel)
    {
        return fullModel["title"] 
                && /[a-z]/i.test(fullModel['title'])
                && Ametys.plugins.web.page.AddPageWizard.getParentId() != null;
    },

    isProcessOk: function(fullModel)
    {
        var value = Ametys.plugins.web.page.AddPageWizard.getInitialConfig('pagetype-blank');
        return (value == true || value == 'true');
    },

	resetModel: function(callback)
	{
        this._model["title"] = Ametys.plugins.web.page.AddPageWizard.getInitialConfig("default-page-title");
        this._model["title-long"] = "";
        
        callback();
	},
	
	updateModel: function()
	{
		this._model["title"] = this._cardPanel.queryById("add-page-title").getValue();
		this._model["title-long"] = this._cardPanel.queryById("add-page-title-long").getValue();
	}
});