/*
 * OpenMRCP - Open Source Media Resource Control Protocol Stack
 * Copyright (C) 2007, Cepstral LLC
 *
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Author(s):
 * Arsen Chaloyan <achaloyan@yahoo.com>
 *
 * Contributor(s):
 *
 */

#include "mrcp_media_agent.h"
#include "mrcp_description.h"

static mrcp_status_t mrcp_media_agent_free_rtp_port_get(mrcp_media_agent_t *agent, mrcp_media_audio_t *media);

mrcp_media_agent_t* mrcp_media_agent_create(
						const mrcp_media_agent_method_set_t *media_method_set, 
						const mrcp_module_method_set_t *module_method_set, 
						void *object,
						apr_pool_t *pool)
{
	mrcp_media_agent_t* agent = apr_palloc(pool,sizeof(mrcp_media_agent_t));
	agent->method_set = media_method_set;
	agent->object = object;

	mrcp_module_init(&agent->module,module_method_set);

	agent->ip = NULL;
	agent->rtp_port_min = 0;
	agent->rtp_port_max = 0;
	agent->rtp_port_cur = 0;

	return agent;
}

mrcp_audio_channel_t* mrcp_audio_channel_create(
									mrcp_audio_channel_mode_t mode,
									mrcp_media_audio_t *local_media,
									mrcp_media_audio_t *remote_media,
									apr_pool_t *pool)
{
	mrcp_audio_channel_t* channel = apr_palloc(pool,sizeof(mrcp_audio_channel_t));
	channel->method_set = NULL;
	channel->object = NULL;
	channel->agent = NULL;
	channel->session = NULL;
	channel->audio_source = NULL;
	channel->audio_sink = NULL;
	channel->mode = mode;

	if(local_media) {
		channel->local_media = local_media;
	}
	else {
		channel->local_media = mrcp_audio_media_create(pool);
	}

	if(remote_media) {
		channel->remote_media = remote_media;
	}
	else {
		channel->remote_media = mrcp_audio_media_create(pool);
	}

	return channel;
}

mrcp_status_t mrcp_media_agent_request(
									mrcp_media_agent_t *agent,
									mrcp_media_audio_t *media,
									apr_pool_t *pool)
{
	media->base.ip = agent->ip;
	mrcp_media_agent_free_rtp_port_get(agent,media);
	media->base.state = MRCP_MEDIA_ENABLED;
	return MRCP_STATUS_SUCCESS;
}

static mrcp_status_t mrcp_media_agent_free_rtp_port_get(mrcp_media_agent_t *agent, mrcp_media_audio_t *media)
{
	media->base.port = agent->rtp_port_cur;
	agent->rtp_port_cur += 2;
	if(agent->rtp_port_cur == agent->rtp_port_max) {
		agent->rtp_port_cur = agent->rtp_port_min;
	}
	return MRCP_STATUS_SUCCESS;
}
