/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

#include "lan.h"

#include <qstringlist.h>

/** Creates a LAN with the given network settings. */
LAN::LAN(IPv4Addr  ip,
			IPv4Netmask  netmask,
			IPv4Addr  gateway,
			QPtrList<IPv4Addr> ns)

	: useDHCP(false),
	  ip(ip),
	  netmask(netmask),
	  gateway(gateway),
	  nameservers(ns)
{
}

/** Creates a LAN that uses DHCP */
LAN::LAN()
	: useDHCP(true)
{
}

/** Creates a LAN object from a string generated
  * by LAN::toString().
  */
LAN  LAN::fromString(const QString& str) {
	LAN  lan;

	QStringList  substrs = QStringList::split('|', str, true);

	/* If DHCP should not be activated, disable it
	 * (It's activated if the default constructor is used)
	 */
	if(!substrs[0].toInt())
		lan.setDHCPEnabled(false);

	QStringList  nsStrList = QStringList::split(',', substrs[4]);
	QStringList::ConstIterator  it = nsStrList.begin();

	QPtrList<IPv4Addr>  nsList;
	while(it != nsStrList.end())
		nsList.append(new IPv4Addr(*it++));

	lan.setIP(substrs[1]);
	lan.setNetmask(substrs[2]);
	lan.setGateway(substrs[3]);
	lan.setDNSList(nsList);

	return  lan;
}

/** Returns a string which describes the LAN.
  * It is possible to transform this string back
  * into a LAN object using LAN::fromString().
  */
QString  LAN::toString() {
	QString  str = "%1|%2|%3|%4|";
	str = str.arg(useDHCP)
			.arg(ip.toString())
			.arg(netmask.toString())
			.arg(gateway.toString());

	IPv4Addr  *ns = nameservers.first();
	while(ns != NULL) {
		str += ns->toString();

		ns = nameservers.next();
		if(ns != NULL)
			str += ',';
	}

	return  str;
}
