/*
* Copyright (C) 2012 Doubango Telecom <http://www.doubango.org>
* License: BSD
* This file is part of Open Source sipML5 solution <http://www.sipml5.org>
*/

tsdp_header_Z.prototype = Object.create(tsdp_header.prototype);
%%{
	machine tsdp_machine_parser_header_Z;

	# Includes
	include tsdp_machine_utils "./tsdp_machine_utils.jrl";
	
	action tag{
		i_tag_start = p;
	}

	action create_zone{
		if(!o_zone){
			o_zone = new tsdp_zone(0, false, null);
		}
	}

	action add_zone{
		if(o_zone){
			hdr_Z.ao_zones.push(o_zone);
			o_zone = null;
		}
	}

	action parse_time{
		if(o_zone){
			o_zone.i_time = tsk_ragel_parser_get_int(s_str, p, i_tag_start);
		}
	}

	action parse_typed_time{
		if(o_zone){
			o_zone.s_typed_time = tsk_ragel_parser_get_string(s_str, p, i_tag_start);
		}
	}

	action shifted{
		if(o_zone){
			o_zone.b_shifted_back = true;
		}
	}	

	fixed_len_time_unit	=  	"d" | "h" | "m" | "s";

	time = DIGIT+ >tag %parse_time;
	typed_time = (DIGIT+ fixed_len_time_unit?) >tag %parse_typed_time;

	Z = 'z' SP* "=" (time SP ("-"%shifted)? typed_time) >create_zone %add_zone 
		(SP time SP ("-"%shifted)? typed_time)* >create_zone %add_zone;
	
	# Entry point
	main := Z :>CRLF?;

}%%

%%write data;

function tsdp_zone(i_time, b_shifted_back, s_typed_time){
	this.i_time = i_time;
	this.b_shifted_back = b_shifted_back;
	this.s_typed_time = s_typed_time;
}

function tsdp_header_Z(i_time, b_shifted_back, s_typed_time){
	tsdp_header.call(this, tsdp_header_type_e.Z);
	this.ao_zones = new Array();
	if(s_typed_time){
		this.ao_zones.push(new tsdp_zone(i_time, b_shifted_back, s_typed_time));
	}

	this.toString = function(){
		var s_str = "";
		for(var i = 0; i < this.ao_zones.length; ++i){

				// time  SP ["-"] typed-time
				s_str += tsk_string_format("{0}{1} {2}{3}",
					i == 0 ? "" : " ",
					this.ao_zones[i].i_time,
					this.ao_zones[i].b_shifted_back ? "-" : "",
					this.ao_zones[i].s_typed_time);
			}

		return s_str;
	}
}

tsdp_header_Z.prototype.Parse = function(s_str){
	var cs = 0;
	var p = 0;
	var pe = s_str.length;
	var eof = pe;
	var data = tsk_buff_str2ib(s_str);
	var i_tag_start;	
	var hdr_Z = new tsdp_header_Z(0, false, null);
	var o_zone = null;
	
	%%write init;
	%%write exec;
	
	if( cs < %%{ write first_final; }%% ){
		tsk_utils_log_error("Failed to parse \"z=\" header: " + s_str);
		return null;
	}
	
	return hdr_Z;
}