package eu.dnetlib.data.collector.plugins.sftp;

import java.util.Iterator;
import java.util.Set;

import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import eu.dnetlib.data.collector.plugin.AbstractCollectorPlugin;
import eu.dnetlib.data.collector.rmi.CollectorServiceException;
import eu.dnetlib.data.collector.rmi.InterfaceDescriptor;

/**
 * Created by andrea on 11/01/16.
 */
public class SftpCollectorPlugin extends AbstractCollectorPlugin {

    private SftpIteratorFactory sftpIteratorFactory;

    @Override
    public Iterable<String> collect(final InterfaceDescriptor interfaceDescriptor, final String fromDate, final String toDate)
            throws CollectorServiceException {
        final String baseUrl = interfaceDescriptor.getBaseUrl();
        final String username = interfaceDescriptor.getParams().get("username");
        final String password = interfaceDescriptor.getParams().get("password");
        final String recursive = interfaceDescriptor.getParams().get("recursive");
        final String extensions = interfaceDescriptor.getParams().get("extensions");

        if ((baseUrl == null) || baseUrl.isEmpty()) {
            throw new CollectorServiceException("Param 'baseurl' is null or empty");
        }
        if ((username == null) || username.isEmpty()) {
            throw new CollectorServiceException("Param 'username' is null or empty");
        }
        if ((password == null) || password.isEmpty()) {
            throw new CollectorServiceException("Param 'password' is null or empty");
        }
        if ((recursive == null) || recursive.isEmpty()) {
            throw new CollectorServiceException("Param 'recursive' is null or empty");
        }
        if ((extensions == null) || extensions.isEmpty()) {
            throw new CollectorServiceException("Param 'extensions' is null or empty");
        }
        if (fromDate != null && !fromDate.matches("\\d{4}-\\d{2}-\\d{2}")) { throw new CollectorServiceException("Invalid date (YYYY-MM-DD): " + fromDate); }

        // final int fromDateIntSeconds =

        return new Iterable<String>() {

            boolean isRecursive = "true".equals(recursive);

            Set<String> extensionsSet = parseSet(extensions);

            @Override
            public Iterator<String> iterator() {
                return getSftpIteratorFactory().newIterator(baseUrl, username, password, isRecursive, extensionsSet, fromDate);
            }

            private Set<String> parseSet(final String extensions) {
                return Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(extensions));
            }
        };
    }

    public SftpIteratorFactory getSftpIteratorFactory() {
        return sftpIteratorFactory;
    }

    public void setSftpIteratorFactory(SftpIteratorFactory sftpIteratorFactory) {
        this.sftpIteratorFactory = sftpIteratorFactory;
    }
}
