/* 
 * Copyright 2014 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.ontel;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import de.avm.android.tr064.exceptions.BaseException;
import de.avm.android.tr064.exceptions.DataMisformatException;
import de.avm.android.tr064.model.PhoneBook;
import de.avm.android.tr064.net.SoapSSLClientFactory;
import de.avm.android.tr064.net.WebUtil;
import de.avm.android.tr064.soap.ISoapCredentials;

/* Soap implementation for the phonebook-Interface */
public class GetPhonebook extends OnTelSoapHelper<PhoneBook>
{
	private String mPhoneBookId;

	/**
	 * Instantiates a new gets the phonebook.
	 * 
	 * @param phoneBookid
	 *            the phone bookid
	 * @param c
	 *            the c
	 */
	public GetPhonebook(ISoapCredentials soapCredentials, String phoneBookid)
	{
		super(soapCredentials);
		mPhoneBookId = phoneBookid;
	}

	@Override
	public PhoneBook getQualifiedResult()
			throws DataMisformatException, BaseException, IOException
	{
		String input = getSoapBody();
		String url = getValueByName("NewPhonebookURL", input);
		
		int port = mSoapCredentials.getPort(true);
		if (port < 1)
			// should not occur, because action used this port
			throw new DataMisformatException("No SSL port available.");

		PhoneBook phoneBook = new PhoneBook(WebUtil.getContentAsInputStream(
				fixDownloadUrl(URLDecoder.decode(url, Charset.defaultCharset().name())),
				SoapSSLClientFactory.getClientWithDigestAuth(port,
						mSoapCredentials.getUsername(), mSoapCredentials.getPassword(),
						mSoapCredentials.getPinningStore())));
		
		// id and name
		phoneBook.setId(mPhoneBookId);
		try
		{
			phoneBook.setName(getValueByName("NewPhonebookName", input));
		}
		catch (DataMisformatException e) {}

		return phoneBook;
	}

	@Override
	public String getSoapMethodParameter()
	{
		return "<NewPhonebookId>" + mPhoneBookId + "</NewPhonebookId>";
	}

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