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

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

/**
 * Execution of a "putTrack" command to copy a file to the server.
 *
 * @version 20030204
 * @author Jörg P. M. Haeger
 */
public class PutTracks extends PutFiles {
	public PutTracks(CDNode CDRootNode, int sessionSizeKB) {
		super(CDRootNode, getSessionSizeKB(CDRootNode, sessionSizeKB));
	}

	protected void editFileName(DirTreeNode node, int index) {
	}

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

	protected void putFile(String dirName, DirTreeNode node)
		throws java.io.IOException, CommandError, Exception {
		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";
		else
		if (file.getName().toLowerCase().endsWith(".ogg"))
			trackType = "ogg";

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

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

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

		FileInputStream inFile = open(file);
		if (inFile == null)
			return;

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

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

			trackType = "continue";
		}

		inFile.close();
	}
}
