package com.jscape.filetransfer;

import java.util.Enumeration;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class RecursiveDeleteOperation
        implements FileTransferOperation {

    private final String remoteDirectory;
    private FileTransfer transfer;

    public RecursiveDeleteOperation(String remoteDirectory) {
        assertNotNull(remoteDirectory);
        this.remoteDirectory = remoteDirectory;
    }

    @Override
    public RecursiveDeleteOperation applyTo(FileTransfer transfer)
            throws FileTransferException {
        assertNotNull(transfer);
        this.transfer = transfer;

        initTransfer();
        deleteRecursive(this.remoteDirectory);

        return this;
    }

    private void initTransfer()
            throws FileTransferException {
        if (!this.transfer.isConnected()) {
            this.transfer.connect();
        }
    }

    private void deleteRecursive(String remoteDirectory)
            throws FileTransferException {
        String currentDirectory = this.transfer.getDir();
        this.transfer.setDir(remoteDirectory);

        Enumeration entries = this.transfer.getDirListing();

        while (entries.hasMoreElements()) {
            FileTransferRemoteFile entry = (FileTransferRemoteFile) entries.nextElement();
            String filename = entry.getFilename();

            if (entry.isDirectory() && (FileTransfer.PARENT_DIRECTORY.equals(filename) || FileTransfer.CURRENT_DIRECTORY.equals(filename))) {
                continue;
            }

            if (entry.isDirectory()) {
                deleteRecursive(filename);
            } else {
                this.transfer.deleteFile(filename);
            }
        }

        this.transfer.setDir(currentDirectory);
        this.transfer.deleteDir(remoteDirectory);
    }
}
