/**
 * Copyright © CENRA (2016)
 *
 * remi.clement@espaces-naturels.fr
 * 
 * This software is a multi-platform and portable application based on 
 * the scientifical toolbox to monitor wetlands. With this toolbox it’s 
 * possible to calculate indicators «RhoMéO» to monitor quality, 
 * fonctionalities and urban and agricultural pressures of wetlands. 
 * Indicators are calculated using naturalist data entered and/or imported,
 * and geographic data downloaded from a geographic server.
 * 
 * This software is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software.  You can  use, 
 * modify and/ or redistribute the software under the terms of the CeCILL
 * license as circulated by CEA, CNRS and INRIA at the following URL
 * "http://www.cecill.info". 
 * 
 * As a counterpart to the access to the source code and  rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty  and the software's author,  the holder of the
 * economic rights,  and the successive licensors  have only  limited
 * liability. 
 * 
 * In this respect, the user's attention is drawn to the risks associated
 * with loading,  using,  modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean  that it is complicated to manipulate,  and  that  also
 * therefore means  that it is reserved for developers  and  experienced
 * professionals having in-depth computer knowledge. Users are therefore
 * encouraged to load and test the software's suitability as regards their
 * requirements in conditions enabling the security of their systems and/or 
 * data to be ensured and,  more generally, to use and operate it in the 
 * same conditions as regards security. 
 * 
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
*/
package fr.cenra.rhomeo.core.preferences.ftp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
public class MockFTPClient extends FTPClient {

    private final Path root;
    private Path workDir;

    public MockFTPClient(final Path root) throws IOException {
        if (!Files.isDirectory(root)) {
            throw new IllegalArgumentException("Input path is not a folder !");
        }

        this.root = root;
        workDir = this.root;
    }

    private Path getPath(final String pathname) {
        if (pathname == null)
            return workDir;
        Path tmp = Paths.get(pathname);
        if (!tmp.isAbsolute()) {
            tmp = workDir.resolve(tmp);
        }

        if (!tmp.startsWith(root)) {
            throw new IllegalArgumentException("Given path does not represents a file of this FTP.");
        }

        return tmp;
    }

    @Override
    public boolean makeDirectory(String pathname) throws IOException {
        Files.createDirectories(getPath(pathname));
        return true;
    }

    @Override
    public boolean changeToParentDirectory() throws IOException {
        if (workDir.equals(root))
            return false;
        workDir = workDir.getParent();
        return true;
    }

    @Override
    public boolean changeWorkingDirectory(String pathname) throws IOException {
        final Path tmpPath = getPath(pathname);
        if (Files.isDirectory(tmpPath)) {
            workDir = tmpPath;
            return true;
        }

        return false;
    }

    @Override
    public FTPFile[] listFiles() throws IOException {
        return listFiles(null, null);
    }

    @Override
    public FTPFile[] listFiles(String pathname) throws IOException {
        return listFiles(pathname, null);
    }

    @Override
    public FTPFile[] listFiles(String pathname, FTPFileFilter filter) throws IOException {
        final Path toList = getPath(pathname);

        final ArrayList<FTPFile> files = new ArrayList<>();
        Files.walkFileTree(toList, Collections.EMPTY_SET, 1, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                final FTPFile ftpFile = convert(file);
                if (filter == null || filter.accept(ftpFile)) {
                    files.add(ftpFile);
                }
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (!dir.equals(toList)) {
                    final FTPFile ftpFile = convert(dir);
                    if (filter == null || filter.accept(ftpFile)) {
                        files.add(ftpFile);
                    }
                }
                return super.preVisitDirectory(dir, attrs);
            }
        });

        return files.toArray(new FTPFile[files.size()]);
    }

    @Override
    public boolean deleteFile(String pathname) throws IOException {
        return Files.deleteIfExists(getPath(pathname));
    }

    @Override
    public OutputStream storeFileStream(String remote) throws IOException {
        return Files.newOutputStream(getPath(remote));
    }

    @Override
    public boolean storeFile(String remote, InputStream local) throws IOException {
        return Files.copy(local, getPath(remote)) > 0;
    }

    @Override
    public InputStream retrieveFileStream(String remote) throws IOException {
        return Files.newInputStream(getPath(remote));
    }

    @Override
    public boolean retrieveFile(String remote, OutputStream local) throws IOException {
        return Files.copy(getPath(remote), local) > 0;
    }

    @Override
    public OutputStream appendFileStream(String remote) throws IOException {
        return Files.newOutputStream(getPath(remote), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    @Override
    public boolean appendFile(String remote, InputStream local) throws IOException {
        final byte[] buffer = new byte[8192];
        int total=0;
        try (final OutputStream out = appendFileStream(remote)) {
            int read = 0;
            while ((read = local.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
                total += read;
            }
        }

        return total > 0;
    }

    /**
     * Convert a path into {@link FTPFile}.
     * @param input Path to see as {@link FTPFile}
     * @return A view of given path through {@link FTPFile} API.
     * @throws IOException If we cannot read attributes of input file.
     */
    private static FTPFile convert(final Path input) throws IOException {
        final BasicFileAttributes attrs = Files.getFileAttributeView(input, BasicFileAttributeView.class).readAttributes();
        final FTPFile ftp = new FTPFile();
        ftp.setName(input.getFileName().toString());
        ftp.setSize(attrs.size());
        final Calendar cal = new GregorianCalendar();
        cal.setTime(new Date(attrs.lastModifiedTime().toMillis()));
        ftp.setTimestamp(cal);
        if (Files.isDirectory(input)) {
            ftp.setType(FTPFile.DIRECTORY_TYPE);
        } else if (Files.isSymbolicLink(input)) {
            ftp.setType(FTPFile.SYMBOLIC_LINK_TYPE);
        } else {
            ftp.setType(FTPFile.FILE_TYPE);
        }

        return ftp;
    }

    @Override
    public boolean completePendingCommand() throws IOException {
        return true;
    }
}
