var FileHandler = function(event) {
	// console.log(event);
	data = event.data;
	// console.log("   -->" + data);
	try {
		var obj = JSON.parse(data);
		switch (obj.action) {
		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 getFileWsUrl = function(host) {
	var prefix = "ws://";
	if (document.location.href.startsWith("https"))
		prefix = "wss://";
	var path = document.location.pathname.lastIndexOf("/");
	path = document.location.pathname.substr(0, path + 1);
	path += "Projects";
	return prefix + host + path;
};
var getHost = function() {
	var host = $("#targetHost");
	if (host.length == 0)
		host = document.location.host;
	else
		host = host[0].value;
	return host;
}
var initFileController = function() {
	
	var host = getHost();
	var url = getFileWsUrl(host);
	url = localStorage.cmaddr;
	// console.log("[ideapi22] addr:" + url);
	var wssocket = new WebSocket(url);
	global.filewssocket = wssocket;
	wssocket.onerror = function(error) {
		console.log(error);
	};
	wssocket.onopen = function(error) {
		var pingObj = {};
		pingObj.action = "ping";
		wssocket.send(JSON.stringify(pingObj));
		listProjects();
		listDumpMemoryDir();
	};
	wssocket.onmessage = FileHandler;

	// ===========init fileTabDiv

	$("#se2").selectmenu();
	$("#tabdiv").editableSelect({
		filter : false
	});
};
var listDumpMemoryDir = function() {
	var pingObj = {};
	pingObj.action = "listProject";
	pingObj.project = "memoryDumps";
	global.filewssocket.send(JSON.stringify(pingObj));
}

// ====== wsHandler

var onListProjects = function(obj) {
	var data = JSON.parse(obj.data);
	global.projects = data;
	var html = "<ul style=\"list-style: none;\">";
	var progressHtml = "<ul style=\"list-style: none; padding-left:0\">";
	for (var i = 0; i < data.length; i++) {
		if (data[i] == "tempZips")
			continue;
		html += "<li  class='ui-widget-content'>" + data[i] + "</li>";
		progressHtml += "<li  class='ui-widget-content'><div class='progressDiv' style='height:100%'></div></li>";
	}
	html += "</ul>"

	$("#projectDiv").html("");
	$("#projectDiv").html(html);
	$("#progressBars").html(progressHtml);
	$("#progressBars ul li")
			.css("height", $("#projectDiv ul li").css("height"));
	$("#progressBars div").progressbar({
		value : 0
	});
	$("#projectDiv ul").selectable(
			{
				stop : function() {
					var result = "";
					global.selectedProjects = [];
					global.selectedProjectIndexs = [];

					$(".ui-selected", this).each(function() {
						var index = $("#projectDiv li").index(this);
						global.selectedProjects.push(this.innerText);
						global.selectedProjectIndexs.push(index);
					});
					// console.log("[cm.js] selectProjectResult:"
					// 		+ global.selectedProjects);
				}
			});
};
var onListProject = function(obj) {
	var html = "";
	var data = JSON.parse(obj.data).subFiles;
	for (var i = 0; i < data.length; i++) {
		html += "<li  class='ui-widget-content'>" + data[i].name + "</li>";
	}
	$("#dumpList").html(html);
	$("#dumpList").selectable({
		stop : function() {
			var result = "";
			global.selectedDumps = [];
			global.selectedDumpIndexs = [];

			$(".ui-selected", this).each(function() {
				var index = $("#projectDiv li").index(this);
				global.selectedDumps.push(this.innerText);
				global.selectedDumpIndexs.push(index);
			});
			// console.log("[cm.js] selectDumpResult:" + global.selectedDumps);
		}
	});

	// console.log("[cmideapi.js] onListProject:" + obj);
}
var onDeleteFile = function(obj) {
	listDumpMemoryDir();
};
var onRenameFile = function(obj) {
	listProjects();
};
var deleteMemory = function() {
	for (var i = 0; i < global.selectedDumps.length; i++) {
		var pingObj = {};
		pingObj.file = "/memoryDumps/" + global.selectedDumps[i];
		pingObj.action = "deleteFile";
		global.filewssocket.send(JSON.stringify(pingObj));
	}
}

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 onSaveFile = function(obj) {
	console.log("onSaveFile");
	// console.log("ToSend.length" + global.toSend.length);
	if (global.toSend == undefined || global.toSend.length == 0) {
		alert("successfully saved!");
		return;
	}
	var pingObj = {};
	pingObj.path = $(".ui-tabs-active").find("a").html();
	pingObj.content = global.toSend;
	pingObj.action = "saveFile";
	pingObj.isAppend = true;
	if (pingObj.content.length > 1024) {
		global.toSend = pingObj.content.substr(1024);
		pingObj.content = pingObj.content.substr(0, 1024);
	} else
		global.toSend = "";
	global.filewssocket.send(JSON.stringify(pingObj));

}

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) {
	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();
	}
};
