/**********************************************************************
* Copyright (C) 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
***********************************************************************/
/*
 * Classes to download active documents and upload saved documents to a server are defined in this file.
 */

var UploadAndDownload = Class.create();
var LoadDocument = Class.create();

UploadAndDownload.prototype = {
	
	documentTranslationWorkspace: null,
	dictionarySelection: null,
	parallelTextSelection: null,
	userDictionary: null,
	loadDocument: null,
	
	initialize: function(uploadButtonID, downloadButtonID,
		dtwObj, dsObj, ptsObj, udObj){
				
		this.uploadButtonElement = $(uploadButtonID);
		this.downloadButtonElement = $(downloadButtonID);
		
		this.documentTranslationWorkspace = dtwObj;
		this.dictionarySelection = dsObj;
		this.parallelTextSelection = ptsObj;
		this.userDictionary = udObj;
		
		this.loadDocument = new LoadDocument();
		
		Event.observe('load-document', 'click', this.openLoadDocumentPane.bind(this));
	},
	
	getUploadButtonElement: function(){
		return this.uploadButtonElement;
	},
	
	getDownloadButtonElement: function(){
		return this.downloadButtonElement;
	},
	
	setValueToDownload: function(targetElementID){
		
		//* targetElementID をIDに持つ要素を取得し、 
		//* その value テキストファイルとしてダウンロードする．
		
		var editorObj;
		var languageObj;
		var dictionaryObj;
		var paralleltextObj;
		var userdictObj;
				
		//* エディター部分の取得処理
		
		new Ajax.Request(
		 './php/ajax/document-translation/getTempFiles.php',
		 {
			 method		:'post',
			 asynchronous	:false,
			 onSuccess	:function(httpObj){
				editorObj = eval("("+httpObj.responseText+")").contents;
			 },
			 onFailure	:function(){
				 alert('Server Error.');
			 },
			 onComplete:function(){
			 }
		 }
		 );
		 
		//* 言語選択部分の取得処理
		languageObj = {
			isThirdLanguageEnabled: this.documentTranslationWorkspace.isEnableThirdLanguage(),
			languages: this.documentTranslationWorkspace.getSelector().getLanguages(),
			tlanslatorIds: this.documentTranslationWorkspace.getSelector().getTranslatorIds()
		};
				
		//* 辞書部分の取得処理
		dictionaryObj = {
			selected: this.dictionarySelection.getIdsOfSelectedResources()
		};
				
		//* 用例対訳部分の取得処理
		
		paralleltextObj = {
			selected: this.parallelTextSelection.getIdOfSelectedResources()
		};
		
		//* ユーザ辞書部分の取得処理
		//* TODO implement
		
		userDictObj = {
			dictName : userDictionary.displayedDictionaryName,
			dictTable: userDictionary.seriarizeDictionaryAsJSON()
		};
				
		var logObj = {
			editor: editorObj,
			language: languageObj,
			dictionary: dictionaryObj,
			paralleltext: paralleltextObj,
			userDict: userDictObj
		};

		$('valueToDownloadLog').value = JSON.encode(logObj);
	},
	
	setUploadedValue: function(log){
		
		//* アップロードされたファイル内の value を適当な文字列にセットする
		//* TODO 現在ドキュメント翻訳に特化しているので、一般化してリファクタリングすべき
		
		var logObj;
		
		try{
			logObj = JSON.decode(log);
			
			editorObj = logObj.editor;
			languageObj = logObj.language;
			dictionaryObj = logObj.dictionary;
			paralleltextObj = logObj.paralleltext;
			userDictObj = logObj.userDict;
			
			if (!languageObj || !dictionaryObj || !paralleltextObj) {
				throw 'Log File does not contain editor, language, dictionary or paralleltext part.';
			}

		} catch(e) {
			alert("Log File Format Error: \n" + e);
			return;
		}
		
		//* 適切にパースされたログを用いて、画面内の表示を更新する
		
		//* 言語対を反映する
		
		this.documentTranslationWorkspace.setValues(
			languageObj.isThirdLanguageEnabled, languageObj.languages, languageObj.tlanslatorIds);
				
		//* エディタ部分を反映する
		//* safariのために、アドレス取得に特別な処理
		var topPageLocation = location.href.substr(0, location.href.lastIndexOf("/"));
		
		if (editorObj) {
		
			var callobj = {
				files: JSON.encode(editorObj)
			};
			
			var hash = $H(callobj);
			var formText = hash.toQueryString();
			var resultObj;
						
			new Ajax.Request(topPageLocation + '/php/ajax/document-translation/setTempFiles.php', {
				method: 'post',
				asynchronous: false,
				parameters: formText,
				onSuccess: function(httpObj){
					resultObj = eval("(" + httpObj.responseText + ")");
				},
				onFailure: function(){
					alert('Server Error.');
				},
				onComplete: function(){
				}
			});
			
			if (resultObj.status == "OK") {
				this.documentTranslationWorkspace.refreshEditorContentsFromServer();
			}
			else {
				alert('Server Error: ' + resultObj.message);
			};
			
		}
				
		//* 辞書を反映する
		
		if (dictionaryObj.selected) {
			var dictID = dictionaryObj.selected;
			
			//* dictID（"#4"など）に対応するボタンを強制的にクリックする
			EventDispatcher.prototype.click($(this.dictionarySelection.getDOMObjFromId(dictID)));
		}
						
		//* 用例対訳を反映する
		
		if (paralleltextObj.selected.length > 0) {
			var paralleltextIDs = paralleltextObj.selected;
			
			//* paralleltextIDsの各要素（"#5"など）に対応するボタンを強制的にクリックする
			
			for (var i = 0; i < paralleltextIDs.length; i++) {
				EventDispatcher.prototype.click($(this.parallelTextSelection.getDOMObjFromId(paralleltextIDs[i])));
			}
		}
		
		//* ユーザ辞書を反映する
		
		if (userDictObj) {
			var dictTable = JSON.decode(userDictObj.dictTable);
		}
		else {
			userDictionary.initialize();
		}
			
		if (dictTable && dictTable.length > 0 && dictTable[0].length > 0) {
			//* 辞書名を反映する
			userDictionary.displayedDictionaryName = userDictObj.dictName;
			UserDictionary.finishLoading("Dictionary was loaded.");
			
			//* テーブルを反映する
			userDictionary.updateTable(dictTable);
		}
		
		this.loadDocument.hidePane();
		
	},
	
	openLoadDocumentPane: function(){
				
		var element = $('load-document');
		var cellPosition = element.cumulativeOffset();
		var bodyPosition = $$('body')[0].cumulativeOffset();
		
		this.loadDocument.showPane(cellPosition[0]-bodyPosition[0]-30,cellPosition[1]-bodyPosition[1]-0+20);
		
	}
}

UploadAndDownload.Event = {
}

//* @classDescription	ローカルファイルからログデータを読み込むボタン
LoadDocument.prototype = {
	//* コンストラクタ
	initialize: function(tbl){
		if ($('load-document-pane')) {
			$('load-document-pane').remove();
		}
		var cd = document.createElement("div");
		cd.id = 'load-document-pane';
		cd.className = 'load-document-box';
		this.paneID = 'load-document-pane';
		new Insertion.Bottom($$('body')[0],cd);
		this.hidePane();
	},
	
	//* データの読み込み
	showPane: function(x,y){
		
		$(this.paneID).setStyle({
			position : 'absolute' ,
			left : x+'px' ,
			top : y+'px' 
		});
		
		$(this.paneID).innerHTML = '';
		var title ='<div class="title">Select a document translation log to upload.</div>';
		var ok = '<form target="dummyframe" id="upload-form" enctype="multipart/form-data" action="./php/ajax/upload.php" method="post">'
				+ '<input type="file" NAME="uploadedFile" id="upload-file" /><br /><br /><input type="submit" NAME="upload" id="upload-log" style="width:140px;" value="Upload Log" class="button-green" />'
				+ '<input type="hidden" value="window.parent.uploadAndDownload.setUploadedValue" name="callbackFunction" id="logCallbackFunction"/>'
				+ '<input id="create-dictionary-cancel-button" type="button" onclick="uploadAndDownload.loadDocument.hidePane();" name="Cancel" value="Cancel" class="button-gray" />'
				+ '</form><iframe id="dummyframe" name="dummyframe" style="display: none;"></iframe>';
		
		$(this.paneID).innerHTML = title + "<br />" +  ok;
		$(this.paneID).show();
	},
	
	hidePane: function(){
		$(this.paneID).hide();
	}
};

