/*
 * @(#)CDNode.java
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2001-2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDcreator.java for details.
 */

import java.io.File;
import javax.swing.tree.DefaultTreeModel;

class CDNode extends DirTreeNode {
	public CDNode(String aName) {
		super(aName);
	}

	public CDNode(File aFile) {
		super(aFile);
	}

	public void clearCache() {
		clear = true;
	}

	protected DirTreeNode createNode(File file) {
		return new CDNode(file);
	}

	protected void expand() {
		super.expand();
//		recount();
//		CDTreeModel.reload();
	}

	public int getNumOfFiles() {
		return numOfFiles;
	}

	public long getSize() {
		return size;
	}

	public void recount() {
		if (isLeaf()) {
			numOfFiles = 1;
			if (Mode.audioCD())
				try {
					size = new Wave(file).getSeconds();
				} catch (Exception e) {
					try {
						size = new MP3(file).getSeconds();
					} catch (Exception e2) {
						if (file instanceof ServerFile)
							size = ((ServerFile)file).getSeconds();
						else
							size = 0;
					}
				}
			else
				size = roundTo2048Blocks(file.length());
			Project.numOfFiles++;
			Project.size += size;
		}
		else
		if (expanded) {
			numOfFiles = 0;
			size = 0;
			for (int i = 0; i < childs.numOfNodes; i++)
			{
				if (State.stopRecount || Project.isTooBig())
					return;
				CDNode child = (CDNode)childs.getNode(i);
				if (clear)
					child.clearCache();
				child.recount();
				numOfFiles += child.getNumOfFiles();
				size += child.getSize();
			}
		}
		else {
			if (clear || numOfFiles == 0) {
				numOfFiles = 0;
				size = 0;
				recount(file);
			}
			else {
				Project.numOfFiles += numOfFiles;
				Project.size += size;
			}
		}
		clear = false;
	}

	private void recount(File file)
	{
		if (!file.isDirectory())
		{
			numOfFiles++;
			size += roundTo2048Blocks(file.length());
			Project.numOfFiles++;
			Project.size += roundTo2048Blocks(file.length());
			return;
		}

		File files[] = ((File2)file).listFiles();
		if (files != null)
			for (int i = 0; i < files.length; i++)
			{
				if (State.stopRecount || Project.isTooBig())
				{
					numOfFiles = 0;
					return;
				}
				recount(files[i]);
			}

		Thread.yield();
	}

	private long roundTo2048Blocks(long n)
	{
		if (n <= 0)
			return 0;
		else
			return 2048 * (((n - 1) / 2048) + 1);
	}

//	static DefaultTreeModel CDTreeModel;
	/** cache the size of the subtrees */
	private boolean clear = true;
	private int numOfFiles = 0;
	private long size = 0;
}
