package com.jscape.inet.ftp;

import com.jscape.util.Assert;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Server feature request.
 *
 * @author Alex
 */
@SuppressWarnings("unchecked")
public final class FeatRequest
        extends AbstractRequest {

    private static final String COMMAND = "FEAT";
    private static final String END_LINE = "211 end";

    private String[] features;

    /**
     * Returns features list.
     *
     * @return features list
     */
    public String[] getFeatures() {
        return (String[]) this.features.clone();
    }

    /**
     * @see com.jscape.inet.ftp.AbstractRequest#isValid()
     */
    public boolean isValid() {
        return true;
    }

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

        interpreter.sendCommand(COMMAND);
        String reply = interpreter.receiveReply();

        assertIsPositive(reply);

        BufferedReader reader = new BufferedReader(new StringReader(reply));
        List features = new ArrayList();
        String line;

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

            while ((line = reader.readLine()) != null && !line.toLowerCase(Locale.ENGLISH).startsWith(END_LINE)) {
                features.add(line);
            }

            this.features = (String[]) features.toArray(new String[0]);
        } catch (Exception e) {
            throw new FtpException(e.getMessage(), e);
        }
    }

}
