package org.xbib.files.ftp.fs.test.server;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.xbib.files.ftp.mock.core.command.Command;
import org.xbib.files.ftp.mock.core.command.ReplyCodes;
import org.xbib.files.ftp.mock.core.session.Session;
import org.xbib.files.ftp.mock.fake.command.AbstractFakeCommandHandler;
import org.xbib.files.ftp.mock.fake.filesystem.FileSystemEntry;

/**
 * A command handler for the MDTM command.
 */
public class MDTMCommandHandler extends AbstractFakeCommandHandler {

    @Override
    protected void handle(Command command, Session session) {
        verifyLoggedIn(session);

        String path = getRealPath(session, command.getParameter(0));

        verifyFileSystemCondition(getFileSystem().exists(path), path, "filesystem.doesNotExist");
        verifyReadPermission(session, path);

        FileSystemEntry entry = getFileSystem().getEntry(path);
        session.sendReply(ReplyCodes.STAT_FILE_OK, getResponse(entry.getLastModified()));
    }

    private String getResponse(Date date) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(date);
    }
}
