
//名前空間用のオブジェクトを用意する
var CONTENTVIEW_FILESYSTEM = {};

$(function () {

	//CONTENTVIEW_FILESYSTEM.fs = null;
	//window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
	//// Initiate filesystem on page load.
	//if (window.requestFileSystem) {
	//	CONTENTVIEW_FILESYSTEM.initFS();
	//}

});

CONTENTVIEW_FILESYSTEM.initFS = function( func ) {
	
	CONTENTVIEW_FILESYSTEM.fs = null;
	
	window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
	// Initiate filesystem on page load.
	if (!window.requestFileSystem) {
		console.log("window.requestFileSystem is null");
		if( func != null ){
			func();
		}
	}
	
	window.requestFileSystem(
			window.TEMPORARY,
			1024*1024,
			function(filesystem) {
				console.log("initFS window.requestFileSystem");
				CONTENTVIEW_FILESYSTEM.fs = filesystem;
				CONTENTVIEW_FILESYSTEM.fs.root.getDirectory('abook', {create: true}, null, CONTENTVIEW_FILESYSTEM.errorHandler);
				
				if( func != null ){
					func();
				}
				
			}, 
			CONTENTVIEW_FILESYSTEM.errorHandler
	);
	
};

CONTENTVIEW_FILESYSTEM.saveFile = function(contentId, fileName, data) {

	if (!CONTENTVIEW_FILESYSTEM.fs) {
		return;
	}
	
	//パス作成
	//var path = "/abook/" + contentId + "/" + fileName;
	CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
			'/abook/' + contentId,
			{create: true},
			function(dirEntry) {
				
				CONTENTVIEW_FILESYSTEM.fs.root.getFile(
						'/abook/' + contentId + "/" + fileName,
						{create: true}, 
						function(fileEntry){
							fileEntry.createWriter(
									function(fileWriter) {
										fileWriter.onwriteend = function(e) {
											console.log('書き込み完了');
										};
										fileWriter.onerror = function(e) {
											console.log('書き込みエラー: ' + e.toString());
										};
										var blobData = new Blob([data], {type:"text/plain"});
										fileWriter.write(blobData);
										
										//var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
										//bb.append(data);
										//fileWriter.write(bb.getBlob('text/plain'));
									}
							);
						},
						CONTENTVIEW_FILESYSTEM.errorHandler
				);
				
			},
			CONTENTVIEW_FILESYSTEM.errorHandler
	);
	
};

CONTENTVIEW_FILESYSTEM.deleteContentDir = function(contentId) {

	if (!CONTENTVIEW_FILESYSTEM.fs) {
		console.log('CONTENTVIEW_FILESYSTEM.fs is null. id=' + contentId);
		return;
	}
	
	CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
			'/abook/' + contentId,
			{},
			function(dirEntry) {
				dirEntry.removeRecursively(
						function() {
							console.log('Directory removed. id=' + contentId);
						},
						CONTENTVIEW_FILESYSTEM.errorHandler
				);
			},
			null
	);
	
};

CONTENTVIEW_FILESYSTEM.checkUpdate = function(contentId, data, func) {
	
	if (!CONTENTVIEW_FILESYSTEM.fs) {
		console.log('CONTENTVIEW_FILESYSTEM.fs is null. id=' + contentId);
		nAjaxLoad++;
		func(data);
		return;
	}
	
	//既にjson.txtが存在するか
	var fileName = contentID + "/json.txt";
	CONTENTVIEW_FILESYSTEM.fs.root.getFile('/abook/' + fileName, { create: false },
		function(fileEntry){
			fileEntry.file(
					function(file){
						var reader = new FileReader();
						reader.onloadend = function(e) {
							console.log("read Json.txt");
							//console.log(e.target.result);
							
							//JSONに戻す
							var jsonObjOld = JSON.parse(e.target.result);
							//配信日時比較
							console.log("OLD:" + jsonObjOld.contentData.lastDeliveryDate)
							console.log("NEW:" + data.contentData.lastDeliveryDate)
							if( jsonObjOld.contentData.lastDeliveryDate != data.contentData.lastDeliveryDate ){
								console.log("違う");
								//ディレクトリ消し
								
								CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
										'/abook/' + contentId,
										{},
										function(dirEntry) {
											dirEntry.removeRecursively(
													function() {
														console.log('Directory removed. id=' + contentId);
														
														//再度書き込み
														CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
																'/abook/' + contentId,
																{create: true},
																function(dirEntry) {
																	
																	CONTENTVIEW_FILESYSTEM.fs.root.getFile(
																			'/abook/' + contentId + "/json.txt",
																			{create: true}, 
																			function(fileEntry){
																				fileEntry.createWriter(
																						function(fileWriter) {
																							fileWriter.onwriteend = function(e) {
																								console.log('JSON書き込み完了');
																								
																								//ファンクション実行
																								nAjaxLoad++;
																								func(data);
																								
																							};
																							fileWriter.onerror = function(e) {
																								console.log('JSON書き込みエラー: ' + e.toString());
																							};
																							var blobData = new Blob([window.JSON.stringify(data)], {type:"text/plain"});
																							fileWriter.write(blobData);
																						}
																				);
																			},
																			CONTENTVIEW_FILESYSTEM.errorHandler
																	);
																	
																},
																CONTENTVIEW_FILESYSTEM.errorHandler
														);
														
													},
													CONTENTVIEW_FILESYSTEM.errorHandler
											);
										},
										null
								);
								
							} else {
								nAjaxLoad++;
								func(data);
							}
							
						};
						reader.readAsText(file);
					}
			);
		},
		function(err){  // 失敗時のコールバック関数
			console.log("NotRead json.txt");
			
			//書き込む
			//パス作成
			//var path = "/abook/" + contentId + "/" + fileName;
			CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
					'/abook/' + contentId,
					{create: true},
					function(dirEntry) {
						
						CONTENTVIEW_FILESYSTEM.fs.root.getFile(
								'/abook/' + contentId + "/json.txt",
								{create: true}, 
								function(fileEntry){
									fileEntry.createWriter(
											function(fileWriter) {
												fileWriter.onwriteend = function(e) {
													console.log('JSON書き込み完了');
													
													//ファンクション実行
													nAjaxLoad++;
													func(data);
													
												};
												fileWriter.onerror = function(e) {
													console.log('JSON書き込みエラー: ' + e.toString());
												};
												var blobData = new Blob([window.JSON.stringify(data)], {type:"text/plain"});
												fileWriter.write(blobData);
												
											}
									);
								},
								CONTENTVIEW_FILESYSTEM.errorHandler
						);
						
					},
					CONTENTVIEW_FILESYSTEM.errorHandler
			);
			
		}
	);
	
}

CONTENTVIEW_FILESYSTEM.errorHandler = function(e) {
	var msg = '';
	switch (e.code) {
	case FileError.QUOTA_EXCEEDED_ERR:
		msg = 'QUOTA_EXCEEDED_ERR';
		break;
	case FileError.NOT_FOUND_ERR:
		msg = 'NOT_FOUND_ERR';
		break;
	case FileError.SECURITY_ERR:
		msg = 'SECURITY_ERR';
		break;
	case FileError.INVALID_MODIFICATION_ERR:
		msg = 'INVALID_MODIFICATION_ERR';
		break;
	case FileError.INVALID_STATE_ERR:
		msg = 'INVALID_STATE_ERR';
		break;
	default:
		msg = 'Unknown Error';
		break;
	};
	//CONTENTVIEW_FILESYSTEM.fs = null;
	alert('Error: ' + msg);
};

