/* 
 * Copyright 2015 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.tam;

import java.io.IOException;
import de.avm.android.tr064.exceptions.BaseException;
import de.avm.android.tr064.exceptions.DataMisformatException;
import de.avm.android.tr064.model.TamInfo;
import de.avm.android.tr064.model.UnsignedNumber;
import de.avm.android.tr064.soap.ISoapCredentials;

/* Soap implementation for the TAM-Interface */
public class GetInfo extends TamSoapHelper<TamInfo>
{
	private int mTamIndex = 0;
	
	/**
	 * @throws IllegalArgumentException
	 * 		illegal value of tamIndex 
	 */
	public GetInfo(ISoapCredentials soapCredentials, int tamIndex)
	{
		super(soapCredentials);
		UnsignedNumber.validateUi2(tamIndex, "tamIndex");
		mTamIndex = tamIndex;
	}

    public int getIndex()
    {
        return mTamIndex;
    }

    /**
     * @param tamIndex
     * 		Index of entry
     * @throws IllegalArgumentException
     * 		illegal value of index
     */
    public GetInfo setIndex(int tamIndex)
    {
        UnsignedNumber.validateUi2(tamIndex, "index");
        mTamIndex = tamIndex;
        return this;
    }

	@Override
	public TamInfo getQualifiedResult()
			throws DataMisformatException, BaseException, IOException
	{
		try
		{
			String input = getSoapBody();

			TamInfo tamInfo = new TamInfo(mTamIndex); 
			tamInfo.setName(getValueByName("NewName", input));
			switch (Integer.parseInt(getValueByName("NewEnable", input)))
			{
				case 0:
					tamInfo.setEnable(false);
					break;
				case 1:
					tamInfo.setEnable(true);
					break;
				default:
					throw new DataMisformatException(getInvalidResponseErrorMessage());
			}
			int status = Integer.parseInt(getValueByName("NewStatus", input));
			if (status > -1)
				tamInfo.setDisplay((status & 0x8000) != 0);
			else
				throw new DataMisformatException(getInvalidResponseErrorMessage());
			
			return tamInfo;
		}
		catch (NumberFormatException exp)
		{
			throw new DataMisformatException(getInvalidResponseErrorMessage(), exp);
		}
	}

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

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