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

public class GetInfo extends MyFritzSoapHelper<MyFritzInfo> {

	public GetInfo(ISoapCredentials soapCredentials) {
		super(soapCredentials);
	}

	@Override
	public MyFritzInfo getQualifiedResult() throws DataMisformatException,
			BaseException, IOException {
		MyFritzInfo fritzInfo = new MyFritzInfo();

		String input = getSoapBody();
		Matcher m = Pattern.compile("<NewEnabled>(.*?)<\\/NewEnabled>")
				.matcher(input);
		try {
			int enable = (m.find()) ? Integer.parseInt(m.group(1)) : -1;
			if (enable == 0)
				fritzInfo.setEnabled(false);
			else if (enable == 1)
				fritzInfo.setEnabled(true);
			else
				throw new DataMisformatException(MISFORMATEXCEPTIONDESCRIPTION);
		} catch (NumberFormatException exp) {
			throw new DataMisformatException(MISFORMATEXCEPTIONDESCRIPTION, exp);
		}

		m = Pattern.compile("<NewDynDNSName>(.*?)<\\/NewDynDNSName>").matcher(
				input);
		if (m.find()) {
			fritzInfo.setDynDNSName(decodeEntities(m.group(1)));
		} else
			throw new DataMisformatException(MISFORMATEXCEPTIONDESCRIPTION);

		m = Pattern.compile("<NewPort>(.*?)<\\/NewPort>").matcher(input);
		if (m.find()) {
			try {
				fritzInfo.setPort(Integer.parseInt(decodeEntities(m.group(1))));
			} catch (NumberFormatException exp) {
				throw new DataMisformatException(MISFORMATEXCEPTIONDESCRIPTION,
						exp);
			}
		} else
			throw new DataMisformatException(MISFORMATEXCEPTIONDESCRIPTION);

		m = Pattern.compile(
				"<NewDeviceRegistered>(.*?)<\\/NewDeviceRegistered>").matcher(
				input);
		try {
			int enable = (m.find()) ? Integer.parseInt(m.group(1)) : -1;
			if (enable == 0)
				fritzInfo.setDeviceRegistered(false);
			else if (enable == 1)
				fritzInfo.setDeviceRegistered(true);
			else
				throw new DataMisformatException(MISFORMATEXCEPTIONDESCRIPTION);
		} catch (NumberFormatException exp) {
			throw new DataMisformatException(MISFORMATEXCEPTIONDESCRIPTION, exp);
		}

		return fritzInfo;
	}

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