package com.jscape.inet.ftp;

import com.jscape.util.Assert;

import java.io.BufferedReader;
import java.io.StringReader;

/**
 * MLST request.
 *
 * @author Alex
 * @version 1.0
 * @see <a href="MLSTRequest.java.html">Source code</a>
 */
public final class MLSTRequest
        extends AbstractRequest {

    private static final String COMMAND = "MLST";
    private static final MLSDParser PARSER = new MLSDParser();

    private String filename;
    private FtpFile file;

    /**
     * Returns current file name.
     *
     * @return current file name
     */
    public String getFilename() {
        return this.filename;
    }

    /**
     * Sets current file name.
     *
     * @param filename current file name
     */
    public void setFilename(String filename) {
        Assert.notNull(filename);
        this.filename = filename;
    }

    /**
     * Returns file instance.
     *
     * @return file instance
     */
    public FtpFile getFile() {
        return this.file;
    }

    /**
     * @see com.jscape.inet.ftp.AbstractRequest#isValid()
     */
    public boolean isValid() {
        return this.filename != null;
    }

    /**
     * @see com.jscape.inet.ftp.AbstractRequest#execute(ClientProtocolInterpreter interpreter)
     */
    public void execute(ClientProtocolInterpreter interpreter)
            throws FtpException {
        Assert.notNull(interpreter);
        assertIsValid();

        String command = this.filename.length() > 0 ? (COMMAND + " " + this.filename) : COMMAND;
        interpreter.sendCommand(command);
        String reply = interpreter.receiveReply();

        assertIsPositive(reply);

        BufferedReader reader = new BufferedReader(new StringReader(reply));

        try {
            reader.readLine(); // skip first line
            String line = reader.readLine();

            if (line == null) {
                throw new Exception("Invalid response.");
            }

            this.file = PARSER.parse(line);
        } catch (Exception e) {
            throw new FtpException(e.getMessage(), e);
        }
    }

}
