/* 
 * Copyright 2012 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.tr064.soap;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.avm.android.tr064.exceptions.BaseException;
import de.avm.android.tr064.exceptions.DataMisformatException;
import de.avm.android.tr064.model.VoIPClientInfo;

/* Soap implementation for the TAM-Interface */
public class GetVoIPConfClientInfo extends VoIPConfSoapHelper<VoIPClientInfo>
{
	private int mIndex = 0;
	private boolean mWithId = false;
	
	public GetVoIPConfClientInfo(ISoapCredentials soapCredentials, int index, boolean withId)
	{
		super(soapCredentials);
		mIndex = index;
		mWithId = withId;
	}

	@Override
	public VoIPClientInfo getQualifiedResult()
			throws DataMisformatException, BaseException, IOException
	{
		String input = getSoapBody();
		VoIPClientInfo clientInfo = new VoIPClientInfo(mIndex); 
		
		Matcher m = Pattern.compile("NewX_AVM-DE_ClientUsername>(.*?)<\\/NewX_AVM-DE_ClientUsername")
				.matcher(input);
		if (m.find())
			clientInfo.setUsername(decodeEntities(m.group(1)));
		else
			throw new DataMisformatException("Invalid Response from VoIPConf Service");
		
		m = Pattern.compile("NewX_AVM-DE_ClientRegistrar>(.*?)<\\/NewX_AVM-DE_ClientRegistrar")
				.matcher(input);
		if (m.find())
			clientInfo.setRegistrar(decodeEntities(m.group(1)));
		else
			throw new DataMisformatException("Invalid Response from VoIPConf Service");

		m = Pattern.compile("NewX_AVM-DE_PhoneName>(.*?)<\\/NewX_AVM-DE_PhoneName")
				.matcher(input);
		if (m.find())
			clientInfo.setName(decodeEntities(m.group(1)));
		else
			throw new DataMisformatException("Invalid Response from VoIPConf Service");

		m = Pattern.compile("NewX_AVM-DE_OutGoingNumber>(.*?)<\\/NewX_AVM-DE_OutGoingNumber")
				.matcher(input);
		if (m.find())
			clientInfo.setOutgoingNumber(decodeEntities(m.group(1)));

		if (mWithId)
		{
			m = Pattern.compile("NewX_AVM-DE_ClientId>(.*?)<\\/NewX_AVM-DE_ClientId")
					.matcher(input);
			if (m.find())
				clientInfo.setId(decodeEntities(m.group(1)));
		}

		return clientInfo;
	}

	@Override
	public String getSoapMethodParameter()
	{
		return "<NewX_AVM-DE_ClientIndex>" + Integer.toString(mIndex) + "</NewX_AVM-DE_ClientIndex>";
	}

	@Override
	public String getSoapMethod()
	{
		if (mWithId) return "X_AVM-DE_GetClient2";
		return "X_AVM-DE_GetClient";
	}
}