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

CONTENTVIEW_FILESYSTEM.fs = null;
CONTENTVIEW_FILESYSTEM.isXhrBusy = false;

//$(function () {
//});

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();
		}
		return;
	}
	
	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},
					function(dirEntry) {
						// /abookディレクトリ作成成功
						if( func != null ){
							func();
						}
					},
					CONTENTVIEW_FILESYSTEM.errorHandler
				);
			}, 
			function(err){  // 失敗時のコールバック関数
				CONTENTVIEW_FILESYSTEM.errorHandler(err);
				if( func != null ){
					func();
				}
			}
	);
	
};

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

	if (!CONTENTVIEW_FILESYSTEM.fs) {
		console.log('CONTENTVIEW_FILESYSTEM.fs is null. id=' + contentId);
		return;
	}
	
	//パス作成
	//var path = "/abook/" + contentId + "/" + fileName;
	CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
			'/abook/' + contentId,
			{create: true},
			function(dirEntry) {
				// /abook/contentId ディレクトリ作成成功
				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);
									}
							);
						},
						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);
		//おまじない ajaxカウントをインクリする必要有り
		//nAjaxLoad++;
		//ファンクションがあれば実行
		if( func != null ){
			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");
							
							//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("Update Content.");
								
								//ディレクトリ消し
								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書き込み完了');
																								
																								//おまじない ajaxカウントをインクリする必要有り
																								nAjaxLoad++;
																								//ファンクション実行
																								if( func != null ){
																									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 {
								
								//おまじない ajaxカウントをインクリする必要有り
								nAjaxLoad++;
								//ファンクション実行
								if( func != null ){
									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書き込み完了');
														
														//おまじない ajaxカウントをインクリする必要有り
														nAjaxLoad++;
														//ファンクション実行
														if( func != null ){
															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.showVideoObjectCache = function(x, y, width, height, src, isFullscreen, contentId, resourceId ){
	
	console.log('CONTENTVIEW_FILESYSTEM.showVideoObjectCache');
	
	if (!CONTENTVIEW_FILESYSTEM.fs) {
		console.log('CONTENTVIEW_FILESYSTEM.fs is null. id=' + contentId);
		showVideoObject(x, y, width, height, src, isFullscreen, true);
		return;
	}
	
	//キャッシュが存在するか確認
	var fileName = contentID + "/res_" + resourceId + ".dat";
	CONTENTVIEW_FILESYSTEM.fs.root.getFile('/abook/' + fileName, { create: false },
		function(fileEntry){
			fileEntry.file(
				function(file){
					console.log("read cache");
					var url = window.URL || window.webkitURL;
					var resSrc = url.createObjectURL(file);
					showVideoObject(x, y, width, height, resSrc, isFullscreen, false);
				}
			);
		},
		function(err){  // 失敗時のコールバック関数
			console.log("NotRead FileSystem");
			
			//キャッシュ化
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function(){
				if (this.readyState == 4 && this.status == 200){
					
					CONTENTVIEW_FILESYSTEM.isXhrBusy = false;
					$('#divImageLoading').css('display', 'none');
					
					//this.response is what you're looking for
					console.log(this.response, typeof this.response);
					
					CONTENTVIEW_FILESYSTEM.fs.root.getFile(
							'/abook/' + fileName,
							{create: true}, 
							function(fileEntry){
								fileEntry.createWriter(
										function(fileWriter) {
											fileWriter.onwriteend = function(e) {
												console.log('RES書き込み完了');
											};
											fileWriter.onerror = function(e) {
												console.log('RES書き込みエラー: ' + e.toString());
											};
											
											var blobData = new Blob([xhr.response], {type:"application/octet-stream"});
											//var blobData = new Blob([this.response], {type:"video/mp4"});
											fileWriter.write(blobData);
											
										}
								);
							},
							CONTENTVIEW_FILESYSTEM.errorHandler
					);
					
				} else {
					if( this.readyState == 2 ){ 
						console.log("onreadystatechange:" + this.readyState + " " + this.status);
						$('#divImageLoading').css('display', 'block');
						CONTENTVIEW_FILESYSTEM.isXhrBusy = true;
					}
				}
			};
			
			if( !CONTENTVIEW_FILESYSTEM.isXhrBusy ){
				xhr.open('GET', src);
				xhr.responseType = 'blob';
				xhr.send();
			} else {
				console.log("xhr is busy.");
			}
			
			//タグは書き出し
			showVideoObject(x, y, width, height, src, isFullscreen, true);
			
		}
	);
	
};


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;
	console.log('FileSystemAPI Error: ' + msg);
	alert('FileSystemAPI Error: ' + msg);
};

