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

import java.io.*;
import java.util.StringTokenizer;
import javax.swing.*;

/**
 * Class to run the "createImage" command
 *
 * @version 20040311
 * @author Jörg P. M. Haeger
 */
public class CreateImage extends BurnSession {
	private OutputStream image = null;
	private int sectors = 0;

	CreateImage() {
		try {
			image = new FileOutputStream(Mode.saveImageAs);
		}
		catch (IOException e) {
		}
	}

	protected JDialog createSuccessDialog() {
		String msg = i18n("saveImageAsResult");
		msg = CDcreator.replaceAll(msg, "@MB@", "" + sectors / 512);
		msg = CDcreator.replaceAll(msg, "@FILE@", Mode.saveImageAs);

		optionPane = new JOptionPane(
			msg,
			JOptionPane.INFORMATION_MESSAGE,
			JOptionPane.DEFAULT_OPTION,
			null, options);
		return optionPane.createDialog(
			CDcreator.mainWin, i18n("titleSaveImageAsResult"));
	}

	protected void execBurnCommand() {
		execCommand("createImage");
		if (image != null)
			try {
				image.close();
			}
			catch (IOException e) {
			}
	}

	protected void execOptions() {
		execFileSystemOptions();
	}

	protected boolean processInternal(int code, String text) {
		final int secSize = 2 * 1024;
		switch (code) {
			case 701:
			try {
				byte[] bs = new byte[secSize];
				int p = 0;
				while (true) {
					int n = CDcreator.inStream.read(bs, p, secSize - p);
					if (n < 0)
						break;
					p += n;
					if (p >= secSize)
						break;
				}
				image.write(bs);
				sectors++;
			}
			catch (IOException e) {
			}
			Version.debug("image", "sectors1 = " + sectors);
			return true;
			case 702:
			try {
				StringTokenizer t = new StringTokenizer(text, " ");
				long length = 0;
				if (t.hasMoreTokens())
					length = Long.parseLong(t.nextToken());
				if (length > 0)
					length = secSize * ((length - 1) / (secSize) + 1);
				if (t.hasMoreTokens()) {
					String name = removeEscChars(t.nextToken());
					Version.debug("image", name + " " + length);
					File file = new File(name);
					if (file.exists()) {
						InputStream in = new FileInputStream(file);
						while (length > 0) {
							byte[] bs = new byte[secSize];
							int n = in.read(bs);
							if (n < 0)
								break;
							if (n > length)
								n = (int) length;
							image.write(bs, 0, n);
							length -= n;
							sectors++;
						}
					}
				}

				byte[] bs = new byte[secSize];
				for (int i = 0; i < bs.length; i++)
					bs[i] = 0;
				while (length > 0) {
					int n = bs.length;
					if (n > length)
						n = (int) length;
					image.write(bs, 0, n);
					length -= n;
					if (length > 0)
						sectors++;
				}
			}
			catch (Exception e) {
			}
			Version.debug("image", "sectors2 = " + sectors);
			return true;
			default:
				;
		}
		return false;
	}
}
