/**********************************************************************
* /js/component/dictionary-creation-undeploy-dictionary.js
* Copyright (C) 2007-2008 Kyoto University
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* 
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-
* 1301  USA
***********************************************************************/

//* Tableの描画には、User dictionary 関係のCSSを再利用
//* 最終的には分割の必要があるかも知れない
//* user-dictionary クラスと undeploy-dictionary-list IDを持つdiv内に作成されることを前提としている．

//* クラスの定義
var UndeployDictionaryService = Class.create();
var DictionaryServiceTable = Class.create();

//* 各種定数の定義
var ID_MESSAGE_AREA_UNDEPLOY = 'undeploy-dictionary-message-area';
var ID_DICTIONARY_TABLE_UNDEPLOY = 'undeploy-dictionary-table';
var ID_DICTIONARY_HEAD_UNDEPLOY = 'undeploy-dictionary-head';
var ID_DICTIONARY_BODY_UNDEPLOY = 'undeploy-dictionary-body';
var ID_OK_UNDEPLOY = 'undeploy-dictionary-ok';

//* 辞書デプロイエリアの大枠のクラス
UndeployDictionaryService.prototype = {
	
	//* 初期化処理
	initialize: function(){
				
		this.messageArea = $(ID_MESSAGE_AREA_UNDEPLOY);
		
		//* 辞書サービスリストのテーブルを作成
		this.refreashDictionaryTable();
		
		//* "Undeploy"ボタンにイベントを割り当て
		Event.observe($(ID_OK_UNDEPLOY), 'click', this.callUndeploy.bind(this));
	},
	
	//* getter,setter
	
	//* 配備済み辞書リストの表示
	refreashDictionaryTable: function(){

		//* 辞書のリストを取得		
		var rowNames = new Array("Service Name", "Service ID", "Original File Name", "Publisher", "Deployed Date");
		
		try {
			var dictList = DictionaryManager.getPublishedDictionaryList();
			
			//* var dictList2 = new Array();
			//* dictList2.push(["Dictionary Part 1", "dict1", "dictionary1.txt", "Masaki Gotou", "2008/10/22"]);
			//* dictList2.push(["Dictionary Part 2", "dict2", "dictionary2.txt", "Satoshi Sakai", "2008/10/20"]);
			//* dictList2.push(["Dictionary Part 3", "dict3", "dictionary3.txt", "Toru Ishida", "2008/10/26"]);
			
			//* 取得したリストを表示
			this.dataTable = new DictionaryServiceTable(rowNames, dictList);
			this.hideLoading();
			$(ID_OK_UNDEPLOY).show();
		}catch(e){			
			this.dataTable = new DictionaryServiceTable(new Array(), new Array());
			if(e == 'User has not login status.'){
				this.finishLoading("Please Login.");
				$(ID_OK_UNDEPLOY).hide();
				
				deployDictionaryService.finishLoading("Please Login.");
				$(ID_OK_DEPLOY).hide();
				downloadDictionaryService.finishLoading("Please Login.");
				$(ID_OK_DOWNLOAD).hide();
			} else {
				this.finishLoading("<font style='color:#FF0000;'>Playground Error: </font>The dictionary list was not loaded correctly. Please try again later.\n"
					+ "Description: " + e);
				$(ID_OK_UNDEPLOY).hide();
				
				deployDictionaryService.finishLoading("<font style='color:#FF0000;'>Playground Error: </font>The dictionary list was not loaded correctly. Please try again later.\n"
					+ "Description: " + e);
				$(ID_OK_DEPLOY).hide();
				downloadDictionaryService.finishLoading("<font style='color:#FF0000;'>Playground Error: </font>The dictionary list was not loaded correctly. Please try again later.\n"
					+ "Description: " + e);
				$(ID_OK_DOWNLOAD).hide();
			}
		}
	},
	
	callUndeploy: function(){
		
		//* 本当にアンデプロイしても良いかを確認．
		if(!window.confirm(
			"Undeployed dictionary service will be deleted from the server and \n"
			+ "cannot be restored without the original dicitonary file.\n\n"
			+ "Are you really sure you want to undeploy the dicitionary service?")) return;
			
		deployDictionaryService.finishLoading("");
		downloadDictionaryService.finishLoading("");
		this.startLoading("Now undeploying...");
		
		//* 実際のアンデプロイを行うメソッドに渡す変数を準備
		var selectedRowArray = this.dataTable.getSelectedRowAsArray();
		
		try {
			if (selectedRowArray) {
				DictionaryManager.undeployDictionary(selectedRowArray[1]);
			
				this.finishLoading('Dictionary service "' + selectedRowArray[1]
					+ '" was successfully undeployed.');
				this.refreashDictionaryTable();
			}
			else {
				this.finishLoading("<font style='color:#FF0000;'>Please select a row.</font>");
			}
		} catch(e) {
			this.finishLoading("<font style='color:#FF0000;'>Undeployment failed </font>" + e);
		}
		
	},
		
	//* 表示用
	startLoading : function( msg ) {
		this.messageArea.show();
		var area = this.messageArea;
		while ( area.firstChild ) area.removeChild( area.firstChild );
		if ( msg ) {
			area.innerHTML = msg;
		}
		var img = new Image();
		img.src = 'img/anime/ajax-loader3.gif';
		area.appendChild( img );
	},

	finishLoading : function( msg ) {
		this.messageArea.show();
		var area = this.messageArea;
		while ( area.firstChild ) area.removeChild( area.firstChild );
		if ( msg ) {
			area.innerHTML = msg;
		}
	},
	
	hideLoading : function(){
		this.messageArea.hide();
	}
};

DictionaryServiceTable.prototype = {
	//* コンストラクタ
	initialize: function(tableHeadArr, cellsArr){
		
		//* Arrayを新たに作成する処理は冗長なので、リファクタリングし削除したい
		this.tableHeadArray = tableHeadArr;		
		this.cellsArray = cellsArr;
		
		this.displayDataTableHead();
		this.displayDataTableBody();
		
		//*クリックしたときは、行選択
		Event.observe($(ID_DICTIONARY_TABLE_UNDEPLOY).down('tbody'), 'click', function(event) {
			var cells;
			if ( this.selectedRowNumber >= 0 ) {
				cells = $(ID_DICTIONARY_TABLE_UNDEPLOY).down('tbody')
				.getElementsByTagName( 'tr' )[this.selectedRowNumber]
				.getElementsByTagName( 'td' );
				for ( var i = cells.length - 1; i >= 0; i-- ) {
					Element.removeClassName( cells[i], 'selectedRow' );
				}
			}
			cells = Event.element( event ).up( 'tr ' ).getElementsByTagName( 'td' );
			for ( var i = cells.length - 1; i >= 0; i-- ) {
				Element.addClassName( cells[i], 'selectedRow' );
			}
			this.selectedRowNumber = parseInt( cells[0].id.split( '_' )[0] );
			
			this.rowSelected = true;
			
		}.bind(this));
	},
	
	//* テーブルヘッダを表示
	displayDataTableHead: function(){
		var headTR = document.createElement('tr');
		
		for(var i=0; i<this.tableHeadArray.length; i++){
			var headTH = document.createElement('th');
			headTH.id = 'tableHeadCell_' + i;
			headTH.innerHTML = this.tableHeadArray[i];
			headTR.appendChild(headTH);
		}
		
		var oldHeadTR = $(ID_DICTIONARY_HEAD_UNDEPLOY).childNodes;
		if(oldHeadTR.length != 0)$(ID_DICTIONARY_HEAD_UNDEPLOY).removeChild(oldHeadTR[0]);
		
		$(ID_DICTIONARY_HEAD_UNDEPLOY).appendChild(headTR);
	},
	
	//* 選択されている行の内容を配列として返す
	getSelectedRowAsArray: function(){
		
		if(this.rowSelected)
			return this.cellsArray[this.selectedRowNumber];
		else
			return null;
	},
	
	//* テーブル本体を表示
	displayDataTableBody: function(){
		
		//* 古いテーブルを削除
		var oldBodyTR = $(ID_DICTIONARY_BODY_UNDEPLOY).childNodes;
		var deleteRowNumber = oldBodyTR.length;
		for(var i=0; i<deleteRowNumber; i++){
			$(ID_DICTIONARY_BODY_UNDEPLOY).removeChild(oldBodyTR[0]);
		}
		
		//* 新しいテーブルを作成
		for(var i=0; i<this.cellsArray.length; i++){
			
			var bodyTR = document.createElement('tr');
			bodyTR.id = 'rowNumber_' + i;
			
			for(var s=0; s<this.cellsArray[i].length; s++){
				var bodyTD = document.createElement('td');
				bodyTD.id = i + "_" + s;
				if(i % 2 == 0){ //* 奇数列
					bodyTD.className = "color1";
				} else {
					bodyTD.className = "color2";
				}
				
				//* 長い文字列が途中で改行されるように、
				//* 全ての文字の間に<wbr>を挿入する。
				var breakableTxt = "";
				for(var charCount=0; charCount<this.cellsArray[i][s].length; charCount++)
					breakableTxt += this.cellsArray[i][s].charAt(charCount) + "<wbr />";
				
				var txtNode = document.createElement("div");
				txtNode.innerHTML = breakableTxt;
				bodyTD.appendChild(txtNode);
				bodyTR.appendChild(bodyTD);
			}
			
			$(ID_DICTIONARY_BODY_UNDEPLOY).appendChild(bodyTR);
		}
	}
};

