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


CONTENTVIEW_FILESYSTEM.initFS = function( func ) {
	
	CONTENTVIEW_FILESYSTEM.fs = null;
	CONTENTVIEW_FILESYSTEM.isXhrBusy = false;
	
	window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
	// Initiate filesystem on page load.
	if (!window.requestFileSystem) {
		//AVWEB.avwLog("window.requestFileSystem is null");
		if( func != null ){
			func();
		}
		return;
	}
	
	window.requestFileSystem(
			window.TEMPORARY,
			1024*1024,
			function(filesystem) {
				AVWEB.avwLog("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) {
		//AVWEB.avwLog('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) {
											//AVWEB.avwLog('書き込み完了');
										};
										fileWriter.onerror = function(e) {
											//AVWEB.avwLog('書き込みエラー: ' + 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) {
		//AVWEB.avwLog('CONTENTVIEW_FILESYSTEM.fs is null. id=' + contentId);
		return;
	}
	
	CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
			'/abook/' + contentId,
			{},
			function(dirEntry) {
				dirEntry.removeRecursively(
						function() {
							//AVWEB.avwLog('Directory removed. id=' + contentId);
						},
						CONTENTVIEW_FILESYSTEM.errorHandler
				);
			},
			null
	);
	
};

CONTENTVIEW_FILESYSTEM.checkUpdate = function(contentId, data, func) {
	
	if (!CONTENTVIEW_FILESYSTEM.fs) {
		//AVWEB.avwLog('CONTENTVIEW_FILESYSTEM.fs is null. id=' + contentId);
		//おまじない ajaxカウントをインクリする必要有り
		//CONTENTVIEW_GENERAL.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) {
							//AVWEB.avwLog("read Json.txt");
							
							//JSONに戻す
							var jsonObjOld = JSON.parse(e.target.result);
							//配信日時比較
							//AVWEB.avwLog("OLD:" + jsonObjOld.contentData.lastDeliveryDate);
							//AVWEB.avwLog("NEW:" + data.contentData.lastDeliveryDate);
							if( jsonObjOld.contentData.lastDeliveryDate != data.contentData.lastDeliveryDate ){
								//AVWEB.avwLog("Update Content.");
								
								//ディレクトリ消し
								CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
										'/abook/' + contentId,
										{},
										function(dirEntry) {
											dirEntry.removeRecursively(
													function() {
														//AVWEB.avwLog('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) {
																								//AVWEB.avwLog('JSON書き込み完了');
																								
																								//おまじない ajaxカウントをインクリする必要有り
																								CONTENTVIEW_GENERAL.nAjaxLoad++;
																								//ファンクション実行
																								if( func != null ){
																									func(data);
																								}
																								
																							};
																							fileWriter.onerror = function(e) {
																								//AVWEB.avwLog('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カウントをインクリする必要有り
								CONTENTVIEW_GENERAL.nAjaxLoad++;
								//ファンクション実行
								if( func != null ){
									func(data);
								}
								
							}
							
						};
						reader.readAsText(file);
					}
				);
			},
			function(err){  // 失敗時のコールバック関数
				//AVWEB.avwLog("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) {
														//AVWEB.avwLog('JSON書き込み完了');
														
														//おまじない ajaxカウントをインクリする必要有り
														CONTENTVIEW_GENERAL.nAjaxLoad++;
														//ファンクション実行
														if( func != null ){
															func(data);
														}
														
													};
													fileWriter.onerror = function(e) {
														//AVWEB.avwLog('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 ){
	
	if (!CONTENTVIEW_FILESYSTEM.fs) {
		//AVWEB.avwLog('CONTENTVIEW_FILESYSTEM.fs is null. id=' + contentId);
		CONTENTVIEW.showVideoObject(x, y, width, height, src, isFullscreen, true);
		return;
	}
	
	//キャッシュが存在するか確認
	var fileName = '/abook/' + contentId + "/res_" + resourceId + ".dat";
	CONTENTVIEW_FILESYSTEM.fs.root.getFile(fileName, { create: false },
		function(fileEntry){
			fileEntry.file(
				function(file){
					//AVWEB.avwLog("read cache");
					var url = window.URL || window.webkitURL;
					var resSrc = url.createObjectURL(file);
					CONTENTVIEW.showVideoObject(x, y, width, height, resSrc, isFullscreen, false);
				}
			);
		},
		function(err){  // 失敗時のコールバック関数
			//AVWEB.avwLog("NotRead FileSystem");
			
			CONTENTVIEW_FILESYSTEM.createMovieCache(src, fileName);
			
			/*
			//キャッシュ化
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function(){
				if (this.readyState == 4 && this.status == 200){
					
					//var size = xhr.getResponseHeader('Content-Length')
					//console.log("size:" + size);
					
					CONTENTVIEW_FILESYSTEM.isXhrBusy = false;
					$('#divImageLoading').css('display', 'none');
					
					//this.response is what you're looking for
					//AVWEB.avwLog(this.response, typeof this.response);
					
					CONTENTVIEW_FILESYSTEM.fs.root.getFile(
							'/abook/' + fileName,
							{create: true}, 
							function(fileEntry){
								fileEntry.createWriter(
										function(fileWriter) {
											fileWriter.onwriteend = function(e) {
												//AVWEB.avwLog('RES書き込み完了');
											};
											fileWriter.onerror = function(e) {
												//AVWEB.avwLog('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 ){ 
						//AVWEB.avwLog("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 {
				//AVWEB.avwLog("xhr is busy.");
			}
			*/
			
			//タグは書き出し
			CONTENTVIEW.showVideoObject(x, y, width, height, src, isFullscreen, true);
			
		}
	);
	
};

CONTENTVIEW_FILESYSTEM.createMovieCache = function(resourceUrl, fileName) {
	
	if (!CONTENTVIEW_FILESYSTEM.fs) {
		return;
	}
	
	//既にビジーなら戻る
	if(CONTENTVIEW_FILESYSTEM.isXhrBusy){
		return;
	}
	
	//キャッシュ化
	var downloadSize = null;
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function(){
		if(this.readyState == 4){
			
			CONTENTVIEW_FILESYSTEM.isXhrBusy = false;
			$('#divCacheLoading').css('display', 'none');
			
			if(this.status == 200){
				//this.response is what you're looking for
				//AVWEB.avwLog(this.response, typeof this.response);
				CONTENTVIEW_FILESYSTEM.fs.root.getFile(
						fileName,
						{create: true}, 
						function(fileEntry){
							fileEntry.createWriter(
									function(fileWriter) {
										fileWriter.onwriteend = function(e) {
											AVWEB.avwLog('RES書き込み完了 size=' + fileWriter.length);
											if(downloadSize){
												//if( downloadSize > AVWEB.avwSysSetting().movieCacheLimitMB * COMMON.MB_BYTE ){
												//	CONTENTVIEW_FILESYSTEM.deleteMovieCache(fileName);
												//} else if( downloadSize != fileWriter.length ){
												//	CONTENTVIEW_FILESYSTEM.deleteMovieCache(fileName);
												//}
												if( downloadSize != fileWriter.length ){
													CONTENTVIEW_FILESYSTEM.deleteMovieCache(fileName);
												}
											}
										};
										fileWriter.onerror = function(e) {
											//AVWEB.avwLog('RES書き込みエラー: ' + e.toString());
										};
										
										var blobData = new Blob([xhr.response], {type:"application/octet-stream"});
										fileWriter.write(blobData);
										
									}
							);
						},
						CONTENTVIEW_FILESYSTEM.errorHandler
				);
			}
		}else if(this.readyState == 2){
			AVWEB.avwLog("onreadystatechange:" + this.readyState + " " + this.status);
			
			downloadSize = xhr.getResponseHeader('Content-Length');
			AVWEB.avwLog("Content-Length:" + downloadSize);
			AVWEB.avwLog("Cachelimit:" + AVWEB.avwSysSetting().movieCacheLimitMB);
			//制限値チェック
			if( AVWEB.avwSysSetting().movieCacheLimitMB == 0 ){
				//無制限
				CONTENTVIEW_FILESYSTEM.isXhrBusy = true;
			} else {
				//制限有り
				if( downloadSize && downloadSize > AVWEB.avwSysSetting().movieCacheLimitMB * COMMON.MB_BYTE ){
					AVWEB.avwLog("CacheLimit abort");
					xhr.abort();
				} else {
					CONTENTVIEW_FILESYSTEM.isXhrBusy = true;
				}
			}
			
			if(CONTENTVIEW_FILESYSTEM.isXhrBusy){
				$('#divCacheLoading').css('z-index', '99999');
				$('#divCacheLoading').css('display', 'block');
			}
			//AVWEB.avwLog("onreadystatechange:" + this.readyState + " " + this.status);
		}
	};
	xhr.onabort = function(e){
		AVWEB.avwLog("XHR 通信中止");
		CONTENTVIEW_FILESYSTEM.isXhrBusy = false;
		$('#divCacheLoading').css('display', 'none');
	};
	
	//var resourceUrl = CONTENTVIEW.downloadResourceById(CONTENTVIEW_GENERAL.contentID);
	if( !CONTENTVIEW_FILESYSTEM.isXhrBusy ){
		xhr.open('GET', resourceUrl);
		xhr.responseType = 'blob';
		xhr.send();
	} else {
		//AVWEB.avwLog("xhr is busy.");
	}
	
};

CONTENTVIEW_FILESYSTEM.deleteMovieCache = function(fileName) {

	if (!CONTENTVIEW_FILESYSTEM.fs) {
		return;
	}
	
	CONTENTVIEW_FILESYSTEM.fs.root.getFile(
		'/abook/' + fileName,
		{ create: false },
		function(fileEntry) {
			fileEntry.remove(
				function() {
					AVWEB.avwLog('File removed. path=' + fileName);
				},
				null
			);
		},
		null
	);
	
};

CONTENTVIEW_FILESYSTEM.clearCache = function() {

	if (!CONTENTVIEW_FILESYSTEM.fs) {
		return;
	}
	
	CONTENTVIEW_FILESYSTEM.fs.root.getDirectory(
			'/abook',
			{},
			function(dirEntry) {
				dirEntry.removeRecursively(
					function() {
						//例外時に呼ばれるので以降fs無効化する
						CONTENTVIEW_FILESYSTEM.fs = null;
					},
					null
				);
			},
			null
	);
	
};

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:' + e.code;
		break;
	};
	//CONTENTVIEW_FILESYSTEM.fs = null;
	//AVWEB.avwLog('FileSystemAPI Error: ' + msg);
	
	//FileSystemのキャッシュクリア
	CONTENTVIEW_FILESYSTEM.clearCache();
	
	alert('FileSystemAPI Error: ' + msg);
	
};

$(function () {
	//CONTENTVIEW_FILESYSTEM.ready();
});

CONTENTVIEW_FILESYSTEM.ready = function(){
	//CONTENTVIEW_FILESYSTEM.fs = null;
	//CONTENTVIEW_FILESYSTEM.isXhrBusy = false;
};

