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

import java.io.File;
import java.io.FileInputStream;

public class PutTracks extends PutFiles
{
	public PutTracks(CDNode CDRootNode, int sessionSize) {
		super(CDRootNode,
			getSessionSize(CDRootNode, sessionSize));
	}

	private static int getSessionSize(
		CDNode node, int sessionSize) {
		if (Mode.audioCD()) {
			// replace seconds by the bytes to transmit
			sessionSize = 0;
			for (int i = 0; i < node.getChildCount(); i++)
				sessionSize += ((CDNode)node.getChildAt(i))
					.getFile().length();
		}
		return sessionSize;
	}

	protected void putFile(String dirName, DirTreeNode node)
		throws java.io.IOException, CommandError
	{
		File file = node.getFile();
		String fileName = dirName + "/" + node.toString();
		Version.debug("PutTracks", "putFile: " + fileName + " " + file);
		view.setMessage(fileName);

		String trackType = "image";
		if (file.getName().toLowerCase().endsWith(".wav"))
			trackType = "wav";
		else
		if (file.getName().toLowerCase().endsWith(".mp3"))
			trackType = "mp3";

		if (file instanceof ServerFile)
		{
			outStream.writeBytes("linkTrack "
				+ spaceToEsc(file.getPath()) + " "
				+ spaceToEsc(trackType) + "\n");
			readResult();
			if (!lastResultOK())
				throw new CommandError();

			if (file.length() > 0)
				bytesTransmitted +=
					1024 * ((file.length() - 1) / 1024 + 1);
			view.setProgress(bytesTransmitted);
			return;
		}

		try {
			new Wave(file);
			trackType = "wav";
		} catch (Exception e) {}

		FileInputStream inFile;
		try {
			inFile = new FileInputStream(file);
		}
		catch (java.io.IOException e) {
			System.out.println("can't read " + file);
			return;
		}

		while (!cancel)
		{
			byte bs[] = new byte[16*1024];
			int len = inFile.read(bs);
			if (len == -1)
				break;
			outStream.writeBytes("putTrack "
				+ trackType + " " + len
				+ "\n");
			outStream.write(bs, 0, len);
			bytesTransmitted += len;
			if (len % 1024 > 0)
				bytesTransmitted += 1024 - len % 1024;
			view.setProgress(bytesTransmitted);

			readResult();
			if (!lastResultOK())
				throw new CommandError();

			trackType = "continue";
		}
	}
}
