/* 
 * 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.net.URLDecoder;
import java.nio.charset.Charset;
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.CallLog;
import de.avm.android.tr064.net.SoapSSLClientFactory;
import de.avm.android.tr064.net.WebUtil;

/* Soap implementation for the calllist-Interface */
public class GetCallList extends OnTelSoapHelper<CallLog>
{
	private int mMaxSize;
	
	/**
	 * Instantiates a new gets the call list.
	 * 
	 * @param c
	 *            a vlid context
	 * @param maxSize
	 *            max count of most recent entries to get
	 */
	public GetCallList(ISoapCredentials soapCredentials, int maxSize)
	{
		super(soapCredentials);
		mMaxSize = maxSize;
	}
	
	@Override
	public CallLog getQualifiedResult()
			throws DataMisformatException, BaseException, IOException
	{
		String input = getSoapBody();
		String url = null;
		Matcher m = Pattern.compile("NewCallListURL>(.*?)<").matcher(input);
		if (m.find())
		{
			int port = mSoapCredentials.getPort(true);
			if (port < 1)
				// should not occur, because action used this port
				throw new DataMisformatException("No SSL port available.");

			url = decodeEntities(m.group(1));
			if (mMaxSize > 0) url += "&max=" + Integer.toString(mMaxSize);
			return new CallLog(WebUtil.getContentAsInputStream(
					fixDownloadUrl(URLDecoder.decode(url, Charset.defaultCharset().name())),
					SoapSSLClientFactory.getClientWithDigestAuth(port,
							mSoapCredentials.getUsername(), mSoapCredentials.getPassword(),
							mSoapCredentials.getTrustedServerCertificates())));
		} else {
			throw new DataMisformatException("Invalid Response from CallList Service");
		}
		
	}

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

}
