/* 
 * 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.TamInfo;

/* Soap implementation for the TAM-Interface */
public class GetTamInfo extends TamSoapHelper<TamInfo>
{
	private int mTamIndex = 0;
	
	/**
	 * Instantiates a new gets a TAM info.
	 * 
	 * @param c
	 *            the c
	 */
	public GetTamInfo(ISoapCredentials soapCredentials, int tamIndex)
	{
		super(soapCredentials);
		mTamIndex = tamIndex;
	}

	@Override
	public TamInfo getQualifiedResult()
			throws DataMisformatException, BaseException, IOException
	{
		String input = getSoapBody();
		TamInfo tamInfo = new TamInfo(mTamIndex); 
		
		Matcher m = Pattern.compile("NewName>(.*?)<\\/NewName").matcher(input);
		if (m.find())
			tamInfo.setName(decodeEntities(m.group(1)));
		else
			throw new DataMisformatException("Invalid Response from TAM Service");
		
		m = Pattern.compile("NewEnable>(.*?)<\\/NewEnable").matcher(input);
		try
		{
			int enable = (m.find()) ? Integer.parseInt(m.group(1)) : -1;
			if (enable == 0)
				tamInfo.setEnable(false);
			else if (enable == 1)
				tamInfo.setEnable(true);
			else
				throw new DataMisformatException("Invalid Response from TAM Service");
		}
		catch(NumberFormatException  exp)
		{
			throw new DataMisformatException("Invalid Response from TAM Service", exp);
		}
		
		m = Pattern.compile("NewStatus>(.*?)<\\/NewStatus").matcher(input);
		try
		{
			int status = (m.find()) ? Integer.parseInt(m.group(1)) : -1;
			if (status > -1)
				tamInfo.setDisplay((status & (int)0x8000) != 0);
			else
				throw new DataMisformatException("Invalid Response from TAM Service");
		}
		catch(NumberFormatException  exp)
		{
			throw new DataMisformatException("Invalid Response from TAM Service", exp);
		}
		
		return tamInfo;
	}

	@Override
	public String getSoapMethodParameter()
	{
		return "<NewIndex>" + Integer.toString(mTamIndex) + "</NewIndex>";
	}

	@Override
	public String getSoapMethod()
	{
		return "GetInfo";
	}
}