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

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

public class GetClient extends VoIPConfSoapHelper<VoIPClientInfo>
{
	private int mIndex = 0;
	private boolean mWithId = false;

    /**
     * @param index index of client to request
     * @throws IllegalArgumentException
     * 		illegal value of index
     */
    public GetClient(ISoapCredentials soapCredentials, int index, boolean withId)
    {
        super(soapCredentials);

        UnsignedNumber.validateUi2(index, "index");

        mIndex = index;
        mWithId = withId;
    }

    public int getIndex()
    {
        return mIndex;
    }

    /**
     * @param index index of client to request
     * @throws IllegalArgumentException
     * 		illegal value of index
     */
    public GetClient setIndex(int index)
    {
        UnsignedNumber.validateUi2(index, "index");

        mIndex = index;
        return this;
    }

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

		VoIPClientInfo clientInfo = new VoIPClientInfo(mIndex); 
		clientInfo.setUsername(getValueByName("NewX_AVM-DE_ClientUsername", input));
		clientInfo.setRegistrar(getValueByName("NewX_AVM-DE_ClientRegistrar", input));
		clientInfo.setName(getValueByName("NewX_AVM-DE_PhoneName", input));
		try
		{
			clientInfo.setOutgoingNumber(getValueByName("NewX_AVM-DE_OutGoingNumber", input));
		}
		catch(DataMisformatException ignored) { }
		if (mWithId)
		{
			try
			{
				clientInfo.setId(getValueByName("NewX_AVM-DE_ClientId", input));
			}
			catch(DataMisformatException ignored) { }
		}		

		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";
	}
}