/*
 * @(#)ServerFile.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.
 *
 * Jörg Haeger, 01.02.2001
 */

import java.io.*;

/**
 * A class to represent remote files.
 *
 * @version 20021023
 * @author Jörg P. M. Haeger
 */
class ServerFile extends File2 {
	public static final int DATA = 0, DIR = 1, MP3 = 2, WAV = 3;

	private int type;
	private long len;
	private long seconds;

	public ServerFile(File parent, String child,
		int type, long len, long seconds) {
		super(parent, child);
		this.type = type;
		this.len = len;
		this.seconds = seconds;
	}

	public ServerFile(String pathname) {
		super(pathname);
		type = DIR;
		len = 0;
	}

	public boolean canRead() {
		return true;
	}

	public String getPath() {
		return super.getPath().replace(separatorChar, '/');
	}

	public long getSeconds() {
		return seconds;
	}

	public int getType() {
		return type;
	}

	public boolean isDirectory() {
		return type == DIR;
	}

	public long length() {
		return len;
	}

	public File[] listFiles() {
		List list = new List();
		list.run(getPath());

		String lines[] = list.getStrings();

		File[] files = new File[lines.length];
		for (int i = 0; i < files.length; i++) {
			try {
				StreamTokenizer tokenizer = new StreamTokenizer(
					new StringReader(lines[i]));
				tokenizer.resetSyntax();
				tokenizer.whitespaceChars(0, 32);
				tokenizer.wordChars(33, 255);

				if (tokenizer.nextToken() != tokenizer.TT_WORD)
					throw new Exception();

				int type = DATA;
				if (tokenizer.sval.equals("d"))
					type = DIR;

				if (tokenizer.nextToken() != tokenizer.TT_WORD)
					throw new Exception();
				long length = Long.parseLong(tokenizer.sval);

				if (tokenizer.nextToken() != tokenizer.TT_WORD)
					throw new Exception();
				String name = Command.removeEscChars(tokenizer.sval);

				long seconds = 0;
				if (tokenizer.nextToken() == tokenizer.TT_WORD)
				if (tokenizer.sval.equals("MP3")) {
					type = MP3;

					if (tokenizer.nextToken() != tokenizer.TT_WORD)
						throw new Exception();
					seconds = Long.parseLong(tokenizer.sval);
				}
				else if (tokenizer.sval.equals("WAV")) {
					type = WAV;

					if (tokenizer.nextToken() != tokenizer.TT_WORD)
						throw new Exception();
					seconds = Long.parseLong(tokenizer.sval);
				}

				files[i] = new ServerFile(
					this, name, type, length, seconds);
			}
			catch (Exception e) {
				files[i] = new ServerFile("Error");
			}
		}

		return files;
	}
}
