exports.Message = Message;
var buffer = require("./buffer");
const head_size = 6;
exports.DecodeMessage = function(buf_reader){

	if(buf_reader.DataSize() < head_size){
		return null;
	}
	var tag = buf_reader.ReadUInt16();
	var len = buf_reader.ReadUInt32();
	if(len > buf_reader.DataSize()){
	
		return null;
	}
	var buf = buf_reader.GetDataBuffer();
	var reader = new buffer.BufferReader( buf.slice(0,len) );
	buf_reader.Grow(len);
	if(create_map[tag]){
		var msg = new create_map[tag]();
		msg.len_ = len;
		msg.DecodeBody(reader);
		return msg;
	}else{
		console.log("no tag creater tag:"+tag);
		throw new Error("no tag creater tag:"+tag);
	}
	return null;
}
var create_map = {};
exports.RegistMessage = function(tag,Class){
	create_map[tag] = Class;
}

function Message(tag){
	this.tag_ = tag;
	this.len_ = -1;
}
Message.prototype.GetTag =  function(){
	return this.tag_;
}
Message.prototype.Length =  function(){
	if(this.len_ == -1) this.len_ = this.BodyLength();
	return head_size + this.len_;
}
Message.prototype.Encode =  function(buf_writer){
	buf_writer.WriteUInt16(this.tag_);
	buf_writer.WriteUInt32(this.len_,2);
	this.EncodeBody(buf_writer);
}


Message.prototype.BodyLength = function(){
	return 0;
}

Message.prototype.DecodeBody = function(buf){
	
}

Message.prototype.EncodeBody = function(buf){
	
}