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

#include "modpartsel.h"

#include <dbsdglobal.h>
#include <mntdevice.h>
#include <dialogs.h>
#include <variables.h>

/* Qt */
#include <qptrlist.h>
#include <qpushbutton.h>
#include <qpixmap.h>
#include <qlistview.h>
#include <qlabel.h>

static const Size::Unit  unit = Size::GB;


modPartSel::modPartSel(QWidget* parent, const char* name)
	: UiModPartSel(parent, name)
{
	lstDevices->setSorting(-1);
}


modPartSel::~modPartSel() {
	if(wasInitialized()) {
		QListViewItem  *child = lstDevices->firstChild();

	  /* Remove only "top-level" devices, they delete their
		* subdevices (slices and partitions) on their own.
		*/
		while(child != NULL) {
			delete  devices.take(child);
			child = child->nextSibling();
		}
	}
}


void modPartSel::initModule()
{
	DBSDIconLoader  *iloader = DBSDGlobal::getIconLoader();
	QPixmap pixHDD = iloader->loadIcon("hdd_unmount", DBSDIconLoader::Size22x22);

	/* Empty lists */
	devices.clear();
	lstDevices->clear();

	MntDevice  *mdev;
	QPtrList<MntDevice>  list = MntDevice::getAllDevices();

	mdev = list.first();
	while(mdev != NULL) {
		switch(mdev->getDeviceType()) {
		case  Device::ATAPI_CD:
		case  Device::SCSI_CD:
		case  Device::Floppy:
			/* Ignore */
			if(list.current() == list.getLast())
				mdev = NULL;
			
			delete list.take();
			
			if(mdev != NULL)
				mdev = list.current();
				
			break;


		default:
			insertMntDev(mdev, mdev->getDesc(), pixHDD);
			mdev = list.next();
			break;
		}
	}
}


void modPartSel::insertMntDev(MntDevice *mdev, const QString& desc, QPixmap pix) {
	QListViewItem  *item = new  QListViewItem(lstDevices,  desc, mdev->getSize().toString(unit));
	item->setPixmap(0, pix);
	devices.insert(item, mdev);

	for(int i = mdev->subdevCount() - 1; i >= 0; --i)
		insertSubDev((*mdev)[i], item);
}


void modPartSel::insertSubDev(MntDevice *mdev,  QListViewItem *item) {
	item->setOpen(true);
	item->setSelectable(false);

	QListViewItem  *subitem = new QListViewItem(item,
															  mdev->getDesc(),
															  mdev->getSize().toString(unit));
															  
	devices.insert(subitem, mdev);
	subitem->setPixmap(0, QPixmap::fromMimeSource("slice.png"));
	subitem->setEnabled(mdev->getFSType() == FSDevice::UFS);
}


void modPartSel::apply() {
	QListViewItem  *curItem = lstDevices->selectedItem();
	MntDevice  *device = devices[curItem];
	if(device != NULL)
	{
		Variables::setValue("disk.activeSlice", device->getName());
		
		/* Set slice's disk name */
		curItem = curItem->parent();
		device = devices[curItem];
		if(device != NULL)
			Variables::setValue("disk.activeDisk", device->getName());
	}
}


bool modPartSel::exitReady() {
	if(lstDevices->selectedItem() == NULL)
		return false;
		
	apply();
	return true;
}
