/*
* Copyright (C) 2012 Doubango Telecom <http://www.doubango.org>
* License: BSD
* This file is part of Open Source sipML5 solution <http://www.sipml5.org>
*/
tsip_header_Contact.prototype = Object.create(tsip_header.prototype);
%%{
	machine tsip_machine_parser_header_Contact;

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

	action create_contact{
		if(!curr_contact){
			curr_contact = new tsip_header_Contact();
		}
	}

	action parse_display_name{
		if(curr_contact){
		    curr_contact.s_display_name = tsk_ragel_parser_get_string(s_str, p, i_tag_start);
            curr_contact.s_display_name = tsk_string_unquote_2(curr_contact.s_display_name);
		}
	}

	action parse_uri{
		if(curr_contact && !curr_contact.o_uri){
		    var s_uri = tsk_ragel_parser_get_string(s_str, p, i_tag_start);
			if((curr_contact.o_uri = tsip_uri.prototype.Parse(s_uri)) && curr_contact.s_display_name){
				curr_contact.o_uri.s_display_name = tsk_strdup(curr_contact.s_display_name);
			}
		}
	}

	action parse_expires{
		if(curr_contact){
		    curr_contact.i_expires = tsk_ragel_parser_get_int(s_str, p, i_tag_start);
		}
	}

	action parse_param{
		if(curr_contact){
		    tsk_ragel_add_param(s_str, p, i_tag_start, curr_contact.ao_params);
		}
	}

	action add_contact{
		if(curr_contact){
		    hdr_contacts.push(curr_contact);
		    curr_contact = null;
		}
	}
	
	action eob{
	}
	
	URI = (scheme HCOLON js_any+)>tag %parse_uri;
	display_name = (( token LWS )+ | quoted_string)>tag %parse_display_name;
	my_name_addr = display_name? :>LAQUOT<: URI :>RAQUOT;
	
	c_p_expires = "expires"i EQUAL delta_seconds>tag %parse_expires;
	contact_extension = (generic_param)>tag %parse_param;
	contact_params = c_p_expires@1 | contact_extension@0;
	contact_param = ( (my_name_addr | URI) :> (SEMI contact_params)* ) >create_contact %add_contact;
	Contact = ( "Contact"i | "m"i ) HCOLON ( STAR | ( contact_param ( COMMA contact_param )* ) );
	
	# Entry point
	main := Contact :>CRLF @eob;

}%%


%%write data;

function tsip_header_Contact(){
	tsip_header.call(this, tsip_header_type_e.Contact);
    this.s_display_name = null;
    this.o_uri = null;
    this.i_expires = -1;
}

tsip_header_Contact.prototype.toString = function(){
    var s_str = tsip_uri_tostring(this.o_uri, true, true);
    if(s_str && this.i_expires >= 0){
        s_str += tsk_string_format(";expires={0}", this.i_expires);
    }
    return s_str;
}

// returns an array of 'Contact' headers
tsip_header_Contact.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_i_tag_start;
	var hdr_contacts = new Array();
	var curr_contact = null;
	
	%%write init;
	%%write exec;
	
	if( cs < %%{ write first_final; }%% ){
		tsk_utils_log_error("Failed to parse 'Contact' header: " + s_str);
		return null;
	}
	
	return hdr_contacts;
}
