/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.io.uri.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.*;
import net.ranides.assira.collection.maps.GenericMap;
import net.ranides.assira.collection.query.CQuery;
import net.ranides.assira.collection.query.CQueryBuilder;
import net.ranides.assira.credentials.UserProperty;
import net.ranides.assira.credentials.UserStore;
import net.ranides.assira.generic.HashUtils;
import net.ranides.assira.io.IOStreams;
import net.ranides.assira.io.InputStreamWrapper;
import net.ranides.assira.io.OutputStreamWrapper;
import net.ranides.assira.io.uri.*;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilters;

/**
 * 
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public class CFTPHandler implements URIHandler {
    
    private final URIResolver resolver;
    
    private final FTPManager man = new FTPManager();
        
    
    public CFTPHandler() {
        this.resolver = URIResolver.DEFAULT;
    }

    public CFTPHandler(URIResolver resolver) {
        this.resolver = resolver;
    }
    
    @Override
    public URIHandle resolve(URI uri) throws IOException {
        return new CFTPHandle(uri);
    }
    
    @Override
    public Collection<String> schemes() {
        return Arrays.asList("ftp");
    }
    
    private class CFTPHandle extends CHandle {
        
        private final URI uri;
        private final String path;
        private final Charset charset;
        private final boolean text;
        private final FTPHostName hostname;
        
        public CFTPHandle(URI uri) {
            this(uri, uri.getPath(), URIUtils.getParam(uri, "charset"));
        }
        
        public CFTPHandle(URI uri, String path, Optional<String> charset) {
            this.uri = uri;
            this.path = path;
            this.charset = Charset.forName(charset.orElse("UTF-8"));
            this.text = charset.isPresent();
            this.hostname = new FTPHostName(uri, resolver.users());
            man.open(hostname);
        }

        @Override
        public void close() throws IOException {
            man.close(hostname);
            super.close();
        }

        @Override
        public URIResolver resolver() {
            return resolver;
        }

        @Override
        public URI uri() throws IOException {
            return uri;
        }

        @Override
        public void move(URIHandle target) throws IOException {
            if(isSameHost(target)) {
                man.shared(hostname).rename(path, target.uri().getPath());
            } else {
                super.move(target);
            }
        }

        @Override
        public void create() throws IOException {
            man.shared(hostname).storeFile(path, IOStreams.EMPTY);
        }

        @Override
        public void delete() throws IOException {
            man.shared(hostname).deleteFile(path);
        }

        @Override
        public OutputStream ostream() throws IOException {
            FTPClient fc = man.fork(hostname);
            return new OutputStreamWrapper(fc.storeFileStream(path)){
                @Override
                public void close() throws IOException {
                    super.close();
                    man.close(hostname, fc);
                }
            };
        }

        @Override
        public InputStream istream(long begin, long end) throws IOException {
            FTPClient fc = man.fork(hostname);
            fc.setRestartOffset(begin);
            return new InputStreamWrapper(IOStreams.limit(fc.retrieveFileStream(path), 0, end)){
                @Override
                public void close() throws IOException {
                    super.close();
                    man.close(hostname, fc);
                }
            };
        }

        @Override
        public InputStream istream() throws IOException {
            return istream(0);
        }

        @Override
        public CQuery<URIHandle> scan() throws IOException {
            FTPFile[] files = man.shared(hostname).listFiles(path, FTPFileFilters.NON_NULL);
            return CQueryBuilder.fromArray(files).map(f -> new CFTPHandle(ireplace(uri, f.getName())));
        }
        
        
        @Override
        public URIHandle parent() throws IOException {
            return new CFTPHandle(iparent(uri));
        }

        @Override
        public long size() throws IOException {
            return stat(path).getSize();
        }

        @Override
        public Instant time(URITime ut) throws IOException {
            if(URITime.MODIFIED.equals(ut)) {
                return stat(path).getTimestamp().toInstant();
            }
            return super.time(ut);
        }

        @Override
        public boolean exists() throws IOException {
            return null != stat(path);
        }

        @Override
        public Set<URIFlags> flags() throws IOException {
            FTPFile stat = stat(path);
            Set<URIFlags> re = URIFlags.collect();
            if(null == stat) {
                return re;
            }
            
            re.add(URIFlags.EXISTS);
            re.add(URIFlags.SIZE);
            if(stat.isDirectory()) {
                re.add(URIFlags.DIR);
            }
            if(stat.isFile()) {
                re.add(URIFlags.FILE);
            }
            if(hasPermission(stat, FTPFile.READ_PERMISSION)) {
                re.add(URIFlags.READABLE);
                re.add(URIFlags.SEEK);
            }
            if(hasPermission(stat, FTPFile.WRITE_PERMISSION)) {
                re.add(URIFlags.WRITABLE);
                re.add(URIFlags.SEEK);
            }
            if(hasPermission(stat, FTPFile.EXECUTE_PERMISSION)) {
                re.add(URIFlags.EXECUTE);
            }
            if(text) {
                re.add(URIFlags.TEXT);
            } else {
                re.add(URIFlags.BINARY);
            }
            
            return re;
        }
        
        @Override
        public Charset charset() throws IOException {
            return charset;
        }

        @Override
        public Path path() throws IOException {
            return Paths.get(path);
        }
                
        private FTPFile stat(String path) throws IOException {
            FTPFile ret = man.shared(hostname).mlistFile(path);
            if(null == ret || !ret.isValid()) {
                return null;
            }
            if(ret.isSymbolicLink()) {
                return stat(ret.getLink());
            }
            return ret;
        }
        
        private boolean hasPermission(FTPFile file, int perm) {
            return
                file.hasPermission(FTPFile.WORLD_ACCESS, perm) ||
                file.hasPermission(FTPFile.GROUP_ACCESS, perm) ||
                file.hasPermission(FTPFile.USER_ACCESS, perm);
        }

        private boolean isSameHost(URIHandle target) {
            return (target instanceof CFTPHandle) && ((CFTPHandle)target).hostname.equals(hostname);
        }

    }

    private static URI iparent(URI uri) {
        String path = uri.getPath();
        String ipath = path.replace('\\', '/');

        int last;
        if(ipath.endsWith("/")) {
            last = ipath.lastIndexOf("/", path.length()-2);
            if(last < 0) {
                return uri;
            }
            return ireplace(uri, path.substring(0, last)+"/");
        } else {
            last = ipath.lastIndexOf("/");
            if(last < 0) {
                return uri;
            }
            return ireplace(uri, path.substring(0, last));
        }
    }
    
    private static URI ireplace(URI uri, String path) {
        try {
            return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, "", "");
        } catch (URISyntaxException cause) {
            throw new AssertionError("Invalid URI: " + path, cause);
        }
    }
    
    private static final class FTPHostName {

        private final int hash;
        private final String host;
        private final Optional<String> user;
        private final Optional<String> pass;
        private final Optional<Integer> port;
        
        public FTPHostName(URI uri, UserStore users) {
            host = uri.getHost();
            Optional<GenericMap<String>> uis = users.match(uri).first();
            if(uis.isPresent()) {
                GenericMap<String> ui = uis.get();
                user = ui.getOptional(UserProperty.LOGIN);
                pass = ui.getOptional(UserProperty.PASSWORD);
            } else {
                user = Optional.empty();
                pass = Optional.empty();
            }
            port = URIUtils.getPort(uri);
            hash = HashUtils.hashValues(5, 23, host, user, pass, port);
        }

        @Override
        public boolean equals(Object object) {
            if(null == object || !FTPHostName.class.equals(object.getClass())) {
                return false;
            }
            FTPHostName that = (FTPHostName)object;
            return 
                host.equals(that.host) &&
                user.equals(that.user) &&
                pass.equals(that.pass) &&
                port.equals(that.port);
        }

        @Override
        public int hashCode() {
            return hash;
        }
        
        public FTPClient connect() throws IOException {
            FTPClient ftp = new FTPClient();
            FTPClientConfig config = new FTPClientConfig();
            ftp.configure(config);

            if(port.isPresent()) {
                ftp.connect(host, port.get());
            } else {
                ftp.connect(host);
            }
            ftp.enterLocalPassiveMode();

            if(user.isPresent()) {
                if(!ftp.login(user.get(),pass.get())) {
                    ftp.disconnect();
                    throw new IOException("FTP E" + ftp.getReplyCode() +": " + ftp.getReplyString());
                }
            }

            return ftp;
        }
        
    }
    
    private static final class FTPManager extends CHandleManager<FTPHostName, FTPClient> {
        
        @Override
        protected void disconnect(FTPClient host) throws IOException {
            host.disconnect();
        }

        @Override
        protected void reset(FTPClient host) throws IOException {
            host.completePendingCommand();
        }

        @Override
        protected FTPClient connect(FTPHostName hostname) throws IOException {
            return hostname.connect();
        }
        
    }
    
}
