/*
*	窗口间消息通信函数
*/

/**
 * [ description]
 * @return {[type]} [description]
 * /**
 * 消息传递
 * @return {[type]} [description]
 *
Message.pop({
	title: 'test2',
	content: '343536',
	position: 12,
	arg: {
		append: true,
		showTime: false,
		action: function(hrefs, $content){

			$content.off().click(function(){

				Message.send(function(hrefs, R){

					Message.send(function(hrefs){

						alert(hrefs.concat(document.location.href).join('\n'));
						window.close();

					}, [hrefs.concat(document.location.href)], R);

				}, [hrefs.concat(document.location.href), PopRelation]);

			});

		},
		actionArg: [[document.location.href], '*$("#content")']
	}
});
 */
var Message = (function() {
	//todo:json数据库
	var startPath = decodeURI(document.location.href.replace(/\/[^\/]+$/, '/').replace('file:///', '')),
		Template = {
			Pop: {
				content: Fso.readUtf8(startPath + 'pop.html'),
				path: startPath + 'pop-temp-$parent-$child.html',
				livePath: '../log/pop-$parent-$child-live.pur5',
				infoPath: '../log/pop-$parent-$child.pur5'
			},
			messagePath: '../log/message-$parent-$child.pur5'
		},

		Relation = getFields({
			parent: 1,
			child: 2
		}, window.location.href, /pop-temp-(\d+)-(\w+)/) || {
			parent: +new Date(),
			child: ''
		},

		myMessagePath = parseData2Template(Template.messagePath, Relation),
		waitForLastChildReturn = false,
		pops = [], //弹出框
		children = {}; //子窗口关系数组

	return {
		init: function() {
			var self = this;
			window.setInterval(function() { //消息扫描
				(function() {
					if (waitForLastChildReturn || pops.length === 0) return;

					var Pop = pops.shift();
					waitForLastChildReturn = Pop.Relation.child;

					Fso.writeUtf8(parseData2Template(Template.Pop.path, Pop.Relation), Template.Pop.content.replace(/swkd3p44op_name/, 'swkd3p44op_' + Pop.Relation.parent + Pop.Relation.child));

					Fso.write(parseData2Template(Template.Pop.infoPath, Pop.Relation), Pop.arg);

					Fso.exec('"' + startPath + 'host32.exe" "' + parseData2Template(Template.Pop.path + '?parent=$parent&child=$child', Pop.Relation) + '"');
				})();

				var msgList = Fso.read(myMessagePath);

				if (!msgList) return;

				Fso.del(myMessagePath);

				msgList.replace(/\/\/action-start\n([\s\S]+?)\/\/action-end/g, function(all, msgBody) {
					eval(msgBody);					
				})
			}, 50);

			if (Relation.child) {
				$(window).on('unload', function() { //删除发给本窗口的消息文件,删除本窗口的生存状态记录文件
					Fso.del(myMessagePath);
					Fso.del(parseData2Template(Template.Pop.livePath, Relation));
				});

				Fso.write(parseData2Template(Template.Pop.livePath, Relation), ' '); //生成本窗口的生存状态记录文件

				this.send(function(childId){
					Message.pushChild(childId);
				}, [Relation.child]);
			} else { //主窗口
				$(window).on('unload', function() { //主窗口关闭时向子窗口发送关闭消息
					$.each(children, function(child, childBody) {
						if (!self.isWindowLive(child)) { //窗口已经关闭不再发送关闭消息
							return;
						}

						self.send(function() {
							window.close();
						}, [], {
							parent: Relation.parent,
							child: child
						});
					});
				});
			}

			return this;
		},
		isWindowLive: function(child) {
			return Fso.fileExists(parseData2Template(Template.Pop.livePath, {
				parent: Relation.parent,
				child: child
			}));
		},
		pushChild: function(child) {
			children[child] = {};
			if (child == waitForLastChildReturn) {
				waitForLastChildReturn = false;
			}
		},
		popChild: function(child) {
			delete children[child];
		},
		pop: function(arg) {
			var self = this;
			var defaultArg = $.extend({}, arg),
				childId;

			delete defaultArg.content;

			childId = $.md5($.stringify(defaultArg), 16);

			var Arg = $.extend(true, {
				tag: '',
				title: false,
				content: '内容',
				position: 9,
				width: 200,
				height: 150,
				arg: {
					token: User.getToken(),
					append: false, //替换||追加信息
					showTime: 1000 * 60 * 2, //2分钟后自动关闭
					action: function(window, $content) {},
					actionArg: []
				}
			}, arg);

			Arg.content = escape(Arg.content);
			Arg.arg.action = escape(jsAction.apply(null, [].concat(Arg.arg.action, Arg.arg.actionArg)));
			delete Arg.arg.actionArg;

			$.extend(true, Arg, Ui.getPosition(Arg.width, Arg.height, Arg.position));

			var NewRelation = {
				parent: Relation.parent,
				child: childId
			};

			if (this.isWindowLive(childId)) {
				self.send(function(content, Arg, action, append){
					updateContent(content, Arg, action, append);
				}, [Arg.content, Arg.arg, Arg.arg.action, Arg.arg.append], NewRelation);
			} else {
				pops.push({
					Relation: NewRelation,
					arg: $.stringify(Arg)
				});
			}
		},
		//send(Function action, Object arg, Relation to)
		send: function(action, args, to) {
			if (typeof(action) != 'function') return;
			Fso.append(parseData2Template(Template.messagePath, to || {
				parent: Relation.parent,
				child: ''
			}),
				'//action-start\n' + jsAction.apply(null, [].concat(action, args)) + '\n//action-end\n');
		}
	}
})().init();