/*
 *  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 tool displays a preview of a survey.
 * @private
 */
 Ext.define('Ametys.plugins.survey.SurveyPreviewTool', {
	extend: 'Ametys.tool.Tool',
	
	/**
	 * @private
	 * @property {String} _surveyId The id of the survew displayed.
	 */
	
	/**
	 * @private
	 * @property {String} _currentPageId The id of the current page in the survew displayed.
	 */
	
	/**
	 * @private
	 * @property {String} _currentQuestionId The id of the current question in the page displayed.
	 */
	
	/**
	 * @private
	 * @property {String} _currentQuestionType The type of the current question in the page displayed.
	 */
	
	/**
	 * @private
	 * @property {String} _mainPanel The main panel of this tool.
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		
		this._hintTpl = new Ext.Template(
				'<div class="title">',
					'<span class="ametysicon-magnifier12"></span>',
					"{title}",
				'</div>',
				'<div class="text">',
					"{{i18n PLUGINS_SURVEY_PREVIEW_TOOL_INTRO}}",
				'</div>'
		);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onMessageCreated, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageModified, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onMessageDeleted, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.SELECTION_CHANGED, this._onMessageSelectionChanged, this);
	},
	
	createPanel: function()
	{
		this._iframe = Ext.create("Ext.ux.IFrame", {}); 
		
		return Ext.create('Ext.Panel', { 
			cls: 'survey-preview-tool',
			border: false,
			layout: 'border',
			scrollable: false,
			
	   	 	items: [{
			   	 		region: 'north',
			   	 		xtype: 'component',
			   	 		cls: 'hint',
			   	 		html: ''
			   	 	},
			   	 	this._iframe
	   	 	]
		});
	},
	
	setParams: function(params)
	{
		this.callParent(arguments);
		
		this._surveyId = params.id;
		this._currentPageId = params.pageId;
		this._currentQuestionId = params.questionId;
		this._currentQuestionType = params.questionType;
		
		this._refreshWithCallback(Ext.bind(this._goToPage, this, [params.pageId, params.questionId]))
	},
	
	refresh: function()
	{
		this._refreshWithCallback(Ext.emptyFn);
	},
	
	/**
	 * Refreshes this tool, and eventually calls a callback function then.
	 * @param {Function} [callBackFn] The callback function.
	 * @private
	 */
	_refreshWithCallback: function(callBackFn)
	{
		this.showRefreshing();
		
		var args = '?id=' + this._surveyId;
		args += '&userLocale=' + encodeURIComponent(Ametys.getAppParameter('user').locale);
		args += '&siteName=' + encodeURIComponent(Ametys.getAppParameter('siteName'));
		args += '&skin=' + encodeURIComponent(Ametys.getAppParameter('skin'));
		
		this._iframe.load(Ametys.CONTEXT_PATH + '/plugins/survey/preview/survey.html' + args)
		
		this.showRefreshed();
		
		Ametys.cms.survey.SurveyDAO.getSurvey([this._surveyId], this._finishRefresh, {scope: this});
	},
	
	/**
	 * Callback function called after retrieving information about the current survey. Updates the title.
	 * @param {Object} response The server response
	 * @private
	 */
	_finishRefresh: function(response)
	{
		this.setTitle(response.label);
		
		this.getContentPanel().items.get(0).update(this._hintTpl.applyTemplate ({title: response.label}));
		
		// Register the tool on the history tool
		var toolId = this.getFactory().getId();
	    var toolParams = this.getParams();

        Ametys.navhistory.HistoryDAO.addEntry({
			id: this.getId(),
			objectId: this.getId(),
			label: this.getTitle(),
			description: this.getDescription(),
			iconSmall: this.getSmallIcon(),
			iconMedium: this.getMediumIcon(),
			iconLarge: this.getLargeIcon(),
			type: Ametys.navhistory.HistoryDAO.TOOL_TYPE,
			action: Ext.bind(Ametys.tool.ToolsManager.openTool, Ametys.tool.ToolsManager, [toolId, toolParams], false)
        });
	},
	
	/**
	 * Shows the given page and even, if provided, the given question in this tool.
	 * @param {String} pageId The page id.
	 * @param {String} [questionId] The question id.
	 * @private
	 */
	_goToPage: function(pageId, questionId)
	{
		if (questionId)
		{
			Ametys.cms.survey.QuestionDAO.getQuestion([questionId], this._goToPageCb, {scope: this, arguments: [pageId, questionId]});
		}
		else
		{
			this._goToPageCb(null, [pageId, questionId])
		}
	},
	
	/**
	 * Updates #property-_currentPageId, #property-_currentQuestionId, #property-_currentQuestionType and shows the given page and question.
	 * @param {Object} question the question retrieved.
	 * @param {Array} args The arguments :
	 * @param {String} args.pageId The page id.
	 * @param {String} [args.questionId] The question id.
	 * @private
	 */
	_goToPageCb: function(question, args)
	{
		var pageId = args[0],
			questionId = args[1];
		
		if (this._iframe.iframeEl.dom.contentWindow.previewGotoPage)
		{
			this._currentPageId = pageId;
			this._currentQuestionId = questionId;
			this._currentQuestionType = question && question.type;
			
			this._iframe.iframeEl.dom.contentWindow.previewGotoPage (pageId, questionId);
		}
	},
	
	getMBSelectionInteraction: function()
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	sendCurrentSelection: function()
	{
		if (this._currentQuestionId)
		{
			var subsubtarget = {
				id: Ametys.message.MessageTarget.SURVEY_QUESTION,
				parameters: {
					id: this._currentQuestionId,
					pageId: this._currentPageId,
					surveyId: this._surveyId,
					type: this._currentQuestionType
				}
			}
		}
		if (this._currentPageId)
		{
			var subtarget = {
				id: Ametys.message.MessageTarget.SURVEY_PAGE,
				parameters: {
					id: this._currentPageId,
					surveyId: this._surveyId
				},
				subtargets: subsubtarget || []
			}
		}
		
		Ext.create('Ametys.message.Message', {
			type: Ametys.message.Message.SELECTION_CHANGED,
			targets: {
				id: Ametys.message.MessageTarget.SURVEY,
				parameters: {
					id: this._surveyId
				},
				subtargets: subtarget || []
			}
		});
	},
	
	/**
     * Listener on creation message.
     * @param {Ametys.message.Message} message The creation message.
     * @private
     */
	_onMessageCreated: function(message)
	{
		var pageTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_PAGE);
		if (pageTarget && pageTarget.getParameters().surveyId == this._surveyId)
		{
			this._refreshWithCallback(Ext.bind(this._goToPage, this, [pageTarget.getParameters().id, null]));
			return;
		}
		
		var questionTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_QUESTION);
		if (questionTarget && questionTarget.getParameters().surveyId == this._surveyId)
		{
			this._refreshWithCallback(Ext.bind(this._goToPage, this, [questionTarget.getParameters().pageId, questionTarget.getParameters().id]));
			return;
		}
	},
	
	/**
     * Listener on edition message.
     * @param {Ametys.message.Message} message The edition message.
     * @private
     */
	_onMessageModified: function(message)
	{
		var surveyTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY);
		if (surveyTarget && surveyTarget.getParameters().id == this._surveyId)
		{
			this.showOutOfDate();
			return;
		}
		
		var pageTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_PAGE);
		if (pageTarget && pageTarget.getParameters().surveyId == this._surveyId)
		{
			this._refreshWithCallback(Ext.bind(this._goToPage, this, [pageTarget.getParameters().id, null]));
			return;
		}
		
		var questionTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_QUESTION);
		if (questionTarget && questionTarget.getParameters().surveyId == this._surveyId)
		{
			this._refreshWithCallback(Ext.bind(this._goToPage, this, [questionTarget.getParameters().pageId, questionTarget.getParameters().id]));
			return;
		}
	},
	
	/**
     * Listener on deletion message.
     * @param {Ametys.message.Message} message The deletion message.
     * @private
     */
	_onMessageDeleted: function(message)
	{
		var surveyTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY);
		if (surveyTarget && surveyTarget.getParameters().id == this._surveyId)
		{
			this.close();
			
			// Remove the deleted survey from the navigation history
			Ametys.navhistory.HistoryDAO.removeEntry (this.getId());
			return;
		}
		
		var pageTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_PAGE);
		if (pageTarget && pageTarget.getParameters().surveyId == this._surveyId)
		{
			this.showOutOfDate();
			return;
		}
		
		var questionTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_QUESTION);
		if (questionTarget && questionTarget.getParameters().surveyId == this._surveyId)
		{
			this._refreshWithCallback(Ext.bind(this._goToPage, this, [questionTarget.getParameters().pageId, null]));
			return;
		}
	},
	
	/**
     * Listener on selection changed message.
     * @param {Ametys.message.Message} message The selection changed message.
     * @private
     */
	_onMessageSelectionChanged: function(message)
	{
		var surveyTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY);
		if (surveyTarget && surveyTarget.getParameters().id == this._surveyId)
		{
			var pageTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_PAGE);
			if (pageTarget)
			{
				var questionTarget = message.getTarget(Ametys.message.MessageTarget.SURVEY_QUESTION);
				this._goToPage(pageTarget.getParameters().id, questionTarget ? questionTarget.getParameters().id : null);
			}
		}
	}
	
 });