var FileHandler = function(event) {
	console.log("[ideapi.js] FileHandler : ");
	// console.log(event);
	data = event.data;
	// console.log("   -->" + data);
	try {
		var obj = JSON.parse(data);
		switch (obj.action) {
		case 'ping':
			console.log("[ideapi.js] FileHandler case 'ping' : ");
		case 'poing':
			break;
		case 'onListProjects':
			onListProjects(obj);
			break;
		case 'onListProject':
			onListProject(obj);
			break;
		case 'onListFile':
			onListFile(obj);
			break;
		case 'onDeleteFile':
			onDeleteFile(obj);
			break;
		case 'onRenameFile':
			onRenameFile(obj);
			break;
		case 'onSaveFile':
			onSaveFile(obj);
		default:
			logComm(obj);
			break;
		}
	} catch (err) {
		console.log(err);
	}

};
var logComm = function(obj) {
	console.log(obj);
};

var initFileController = function() {
	global.filewssocket = global.wssocket;
	// ===========init fileTabDiv
	global.fileTab = $("#fileTabDiv").tabs();
	global.tabCounter = 0;
	global.tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
	global.fileContentMap = new Map();
	global.fileContentMap.set("Hello", "<------ select Contract  ");
	global.fileTab.on("click", "span.ui-icon-close", function() {
		var panelId = $(this).closest("li").remove().attr("aria-controls");
		$("#" + panelId).remove();
		global.fileTab.tabs("refresh");
	});
	global.fileTab.on("tabsbeforeactivate", function(event, ui) {
		global.tempevent = event;
		global.tempui = ui;
		var oldKey = ui.oldTab.find("a").html();
		var oldContent = global.scriptEditor.getValue();
		global.fileContentMap.set(oldKey, oldContent);
		var key = ui.newTab.find("a").html();
		// console.log("oldkey:" + oldKey + " --> key:" + key);
		var content = global.fileContentMap.get(key);
		global.scriptEditor.setValue(content);
	});

	global.fileTab.on("keyup", function(event) {
		if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
			var panelId = tabs.find(".ui-tabs-active").remove().attr(
					"aria-controls");
			$("#" + panelId).remove();
			tabs.tabs("refresh");
		}
	});
	$("#se2").selectmenu();
	$("#tabdiv").editableSelect({
		filter : false
	});
};
function addTab(args) {
	var label = args.title || "Tab " + global.tabCounter, id = "tabs-"
			+ global.tabCounter, li = $(global.tabTemplate.replace(
			/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label)), tabContentHtml = args.content;

	global.fileTab.find(".ui-tabs-nav").append(li);
	global.fileTab.append("<div id='" + id + "'></div>");
	global.fileTab.tabs("refresh");
	global.tabCounter++;
	li.find("a").click();
}

// ====== wsHandler

var onListProjects = function(obj) {
	var data = JSON.parse(obj.data);	
	global.projects = data;
	var html = "";
	for (var i = 0; i < data.length; i++) {
		html += "<h3 onclick=\"switchProject(" + i
				+ ")\" class='projectButton'>&nbsp;&nbsp;" + data[i] + "</h3>";
		html += "<div id='projectContent" + i
				+ "' class='projectTreeDiv'></div>";
	}
	$("#projectDiv").html("");
	$("#projectDiv").html(html);
	
	$("#projectDiv").accordion({
		heightStyle : "content"
	});
	$("#projectDiv").accordion("refresh");
	$.contextMenu({
		selector : '.projectButton',
		zIndex : 10,
		callback : function(key, options) {
			var projectName = this.html().replace(/.*&nbsp;/g, "");
			global.projectName = projectName;
			// console.log("key:" + key + " projectName:" + projectName);
			if (key == "Rename") {
				$("#dialogContent").html("<input value='输入新文件名'></input>");
				$("#dialog").dialog({
					autoOpen : false,
					modal : true,
					title : ("Rename File:" + projectName),
					buttons : {
						"Rename" : renameFile,
						Cancel : function() {
							$("#dialog").dialog("close");
						}
					},
					close : function() {
					}
				});
				$("#dialog").dialog("open");
			} else if (key == "Delete") {
				$("#dialogContent").html("是否删除项目:" + projectName);
				$("#dialog").dialog({
					autoOpen : false,
					title : ("Delete File:" + projectName),
					modal : true,
					buttons : {
						"Delete" : deleteFile,
						Cancel : function() {
							$("#dialog").dialog("close");
						}
					},
					close : function() {
					}
				});
				$("#dialog").dialog("open");
			} else if (key == "Create File") {
				$("#dialogContent").html("<input value='输入文件名'></input>");
				$("#dialog").dialog({
					autoOpen : false,
					modal : true,
					title : ("Create File"),
					buttons : {
						"Create" : createFile,
						Cancel : function() {
							$("#dialog").dialog("close");
						}
					},
					close : function() {
					}
				});
				$("#dialog").dialog("open");
			} else if (key == "Create Folder") {
				$("#dialogContent").html("<input value='输入文件夹名'></input>");
				$("#dialog").dialog({
					autoOpen : false,
					modal : true,
					title : ("Create File"),
					buttons : {
						"Create" : createFolder,
						Cancel : function() {
							$("#dialog").dialog("close");
						}
					},
					close : function() {
					}
				});
				$("#dialog").dialog("open");
			} else if (key == "Upload File") {
				$("#uploadFileInput").click();

			}
		},
		items : {
			"New" : {
				name : "New",
				icon : "add",
				items : {
					"Create File" : {
						name : "Create File",
						icon : "copy"
					},
					"Create Folder" : {
						name : "Create Folder",
						icon : "paste"
					},
					"Upload File" : {
						name : " Upload File",
						icon : "loading"
					}

				}
			},
			"Rename" : {
				name : "Rename",
				icon : "edit"
			},
			"Delete" : {
				name : "Delete",
				icon : "delete"
			}

		}
	});
};
var uploadFile = function(obj) {
	var file = $("#uploadFileInput")[0].files[0];
	var chunks = sliceFile(file);
	global.chunks = chunks;
	global.uploadedChunk = 0;
	global.startUpload = new Date().getTime();
	uploadChunks();

};
var uploadChunks = function() {
	var file = $("#uploadFileInput")[0].files[0];
	var percent = global.uploadedChunk * 100 / global.chunks.length;
	percent = percent.toFixed(2);
	$("#uploadProcess").html("upload:" + percent + "%");
	if (global.uploadedChunk < global.chunks.length) {
		let fd = new FormData();
		var chunk = global.chunks[global.uploadedChunk];
		fd.append("file", chunk);
		$.ajax({
			url : './Upload?dirName=' + global.projectName + "&fileName="
					+ file.name + "&order=" + global.uploadedChunk + "&count="
					+ global.chunks.length,
			type : 'POST',
			data : fd,
			processData : false, // tell jQuery not to process the data
			contentType : false, // tell jQuery not to set contentType
			success : function(data) {
				global.uploadedChunk++;
				uploadChunks();
			},
			error : function(data) {
				console.log("[uploadFile] error!");
				alert("Upload failed!");
			}
		});
	} else {
		$("#uploadProcess").html("upload:100%");
		listProjects();
		setTimeout(function() {
			alert("Upload finished, spends "
					+ (new Date().getTime() - global.startUpload) + "ms");
			$("#uploadProcess").html("");
			
		}, 100);
	}
	return;
};
var sliceFile = function(file) {
	let piece = 1024 * 50;
	let totalSize = file.size; // 文件总大小
	let start = 0; // 每次上传的开始字节
	let end = start + piece; // 每次上传的结尾字节
	let chunks = []
	while (start < totalSize) {
		// 根据长度截取每次需要上传的数据
		// File对象继承自Blob对象，因此包含slice方法
		let blob = file.slice(start, end);
		chunks.push(blob)
		start = end;
		end = start + piece;
	}
	return chunks;
};

var onDeleteFile = function(obj) {
	listProjects();
};
var onRenameFile = function(obj) {
	listProjects();
};
var deleteFile = function() {
	var pingObj = {};
	pingObj.file = global.projectName;
	pingObj.action = "deleteFile";
	$("#dialog").dialog("close");
	global.filewssocket.send(JSON.stringify(pingObj));

	$("#dialog").dialog("close");
};
var renameFile = function() {
	var pingObj = {};
	pingObj.oldFile = global.projectName;
	pingObj.newFile = global.projectName.replace(/[^\/]*$/g, "")
			+ $("#dialog").find("input")[0].value;
	pingObj.action = "renameFile";
	$("#dialog").dialog("close");
	global.filewssocket.send(JSON.stringify(pingObj));

};
var createFile = function() {
	var newFileName = $("#dialog").find("input")[0].value;
	createFileInternal(global.projectName, newFileName, false);
	$("#dialog").dialog("close");
};
var createFolder = function() {
	var newFileName = $("#dialog").find("input")[0].value;
	createFileInternal(global.projectName, newFileName, true);
	$("#dialog").dialog("close");
};
var createFileInternal = function(dir, name, isFolder) {
	var pingObj = {};
	pingObj.dir = dir;
	pingObj.name = name;
	pingObj.isFolder = isFolder;
	pingObj.action = "createFile";
	global.filewssocket.send(JSON.stringify(pingObj));
};
var clickProjectDir = function() {
	console.log("TOOD: clickProjectDir");
}

var saveContract = function() {
	var pingObj = {};
	pingObj.isAppend = false;
	pingObj.path = $(".ui-tabs-active").find("a").html();
	pingObj.content = global.scriptEditor.getValue();
	pingObj.action = "saveFile";
	// console.log(pingObj);
	if (pingObj.path == "Hello") {
		alert("We can't save 'Hello'");
		return;
	}

	global.filewssocket.send(JSON.stringify(pingObj));
};
var onSaveFile = function(obj) {
	console.log("onSaveFile");

	alert("save result:" + obj.data);
	return;

}

var onListProject = function(obj) {
	var data = JSON.parse(obj.data);
	var title = global.projects[global.lastClickedProjectId];
	if (!data.isDir) {

		global.fileContentMap.set(title, data.val);
		$(".projectTreeDiv").css("padding", "0");
		addTab({
			"title" : title
		});
	} else {
		var listDiv = $("#projectContent" + global.lastClickedProjectId);
		listDiv.html(getProjectTreeHtml(data, "projectTreeUl", "/" + title
				+ "/"));
		$(".projectTreeUl").menu();
		$.contextMenu({
			selector : '.projectFileDiv',
			zIndex : 10,
			callback : function(key, options) {
				var projectName = this[0].onclick + "";
				projectName = projectName.split("\n")[1];
				projectName = projectName.replace(/^[^"]*"/g, "").replace(
						/".*$/g, "");
				global.projectName = projectName;
				if (key == "Rename") {
					$("#dialogContent").html(
							"<input value='" + projectName.replace(/.*\//g, "")
									+ "'></input>");
					$("#dialog").dialog({
						autoOpen : false,
						modal : true,
						title : ("Rename File:" + projectName),
						buttons : {
							"Rename" : renameFile,
							Cancel : function() {
								$("#dialog").dialog("close");
							}
						},
						close : function() {
						}
					});
					$("#dialog").dialog("open");
				} else if (key == "Delete") {
					$("#dialogContent").html("是否删除项目:" + projectName);
					$("#dialog").dialog({
						autoOpen : false,
						title : ("Delete File:" + projectName),
						modal : true,
						buttons : {
							"Delete" : deleteFile,
							Cancel : function() {
								$("#dialog").dialog("close");
							}
						},
						close : function() {
						}
					});
					$("#dialog").dialog("open");
				} else if (key == "Create File") {
					$("#dialogContent").html("<input value='输入文件名'></input>");
					$("#dialog").dialog({
						autoOpen : false,
						modal : true,
						title : ("Create File"),
						buttons : {
							"Create" : createFile,
							Cancel : function() {
								$("#dialog").dialog("close");
							}
						},
						close : function() {
						}
					});
					$("#dialog").dialog("open");
				} else if (key == "Create Folder") {
					$("#dialogContent").html("<input value='输入文件夹名'></input>");
					$("#dialog").dialog({
						autoOpen : false,
						modal : true,
						title : ("Create File"),
						buttons : {
							"Create" : createFolder,
							Cancel : function() {
								$("#dialog").dialog("close");
							}
						},
						close : function() {
						}
					});
					$("#dialog").dialog("open");
				} else if (key == "Upload File") {
					$("#uploadFileInput").click();
				}

			},
			items : {
				"New" : {
					name : "New",
					icon : "add",
					items : {
						"Create File" : {
							name : "Create File",
							icon : "copy"
						},
						"Create Folder" : {
							name : "Create Folder",
							icon : "paste"
						},
						"Upload File" : {
							name : " Upload File",
							icon : "loading"
						}

					}
				},
				"Rename" : {
					name : "Rename",
					icon : "edit"
				},
				"Delete" : {
					name : "Delete",
					icon : "delete"
				}

			}
		});

	}
};
var onListFile = function(obj) {
	var data = JSON.parse(obj.data);
	global.fileContentMap.set(data.path, data.val);
	$(".projectTreeDiv").css("padding", "0");
	addTab({
		"title" : data.path
	});
};
var getProjectTreeHtml = function(data, clz, preFix) {
	if (data == undefined || data.subFiles == undefined)
		return "";
	var ret = "<ul class='" + clz + "'>";
	for (var i = 0; i < data.subFiles.length; i++) {
		var obj = data.subFiles[i];
		var clickfun = "";
		if (obj.subFiles == undefined) {
			clickfun = "onclick = 'clickProjectFile(\"" + preFix + obj.name
					+ "\")'" + " class='projectFileDiv' ";
		} else {
			clickfun = "onclick ='clickProjectDir(\"" + preFix + obj.name
					+ "\")'" + " class='projectFileDiv'";
		}
		ret += "<li><div " + clickfun + ">" + obj.name + "</div>";
		if (obj.subFiles != undefined)
			ret += getProjectTreeHtml(obj, "subFileTreeUl", preFix + obj.name
					+ "/");
		ret += "</li>"
	}
	return ret + "</ul>";
};
// ====== wsHandler done!

var clickProjectFile = function(tar) {
	var pingObj = {};
	pingObj.action = "listFile";
	pingObj.path = tar;
	if (global.fileContentMap.has(pingObj.path)) {
		clickTab(pingObj.path);
	} else {
		global.filewssocket.send(JSON.stringify(pingObj));

	}
};
var listProjects = function(off) {
	console.log("[ideapi.js] listProjects : ");
	var pingObj = {};
	pingObj.action = "listProjects";
	global.filewssocket.send(JSON.stringify(pingObj));
}

var switchProject = function(i) {
	var pingObj = {};
	pingObj.action = "listProject";
	pingObj.project = global.projects[i];
	global.lastClickedProjectId = i;
	if (global.fileContentMap.has(pingObj.project)) {
		clickTab(pingObj.project);
	} else
		global.filewssocket.send(JSON.stringify(pingObj));
};
var clickTab = function(title) {
	// console.log("clickTab:" + title);
	var tabs = global.fileTab.find("a");
	for (var i = 0; i < tabs.size(); i++) {
		if ($(tabs[i]).html() == title)
			$(tabs[i]).click();
	}
};
