package eu.dnetlib.data.download.rmi;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.Resource;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import eu.dnetlib.data.download.DownloadPluginEnumeratorImpl;
import eu.dnetlib.data.download.DownloadReport;
import eu.dnetlib.data.download.DownloadReportMap;
import eu.dnetlib.data.download.DownloadServiceImpl;
import eu.dnetlib.data.download.worker.DownloadWorker;
import eu.dnetlib.data.objectstore.modular.connector.ObjectStore;
import eu.dnetlib.data.objectstore.modular.connector.ObjectStoreDao;
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
import eu.dnetlib.data.objectstore.rmi.Protocols;
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * The Class DownloadServiceFeeder.
 */
public class DownloadServiceFeeder {

	/** The Constant log. */
	private static final Log log = LogFactory.getLog(DownloadServiceFeeder.class);
	private static final int MAX_NUM_FOUND = 10;

	/** The download plugin enumerator. */
	@Resource
	DownloadPluginEnumeratorImpl downloadPluginEnumerator;

	/** The result set client factory. */
	@Resource
	private ResultSetClientFactory resultSetClientFactory;

	/** The object store dao. */
	@Autowired
	private ObjectStoreDao objectStoreDao;

	public static void reportException(final DownloadReportMap report, final DownloadItem di, final Throwable e) {
		final String className = e.getClass().getName();
		if (!report.containsKey(className)) {
			final DownloadReport dr = new DownloadReport();
			dr.setStackTrace(Joiner.on("\tat ").join(e.getStackTrace()));
			if (di != null) {
				dr.setDownloadItem(di);
			}
			report.put(className, dr);
		} else {
			report.get(className).incrementError();
		}
	}

	/**
	 * Download and feed file into the objectStore .
	 *
	 * @param epr
	 *            the end-point reference of the result-set of Serialized DownloadItem
	 * @param plugin
	 *            the plugin used to retrieve the correct URL
	 * @param objectStoreID
	 *            the object store id to store the data
	 * @param protocol
	 *            the protocol used to download the file
	 * @param mimeType
	 *            the mime type of the Files
	 * @param numberOfThreads
	 *            the number of threads to use for download at the same time
	 * @throws DownloadServiceException
	 *             the download service exception
	 * @throws ObjectStoreServiceException
	 */
	public DownloadReportMap download(final String epr,
			final String plugin,
			final String objectStoreID,
			final String protocol,
			final String mimeType,
			final int numberOfThreads,
			final String basePath,
			final List<String> regularExpression,
			final int connectTimeoutMs,
			final int readTimeoutMs, final int sleepTimeMs) throws DownloadServiceException, ObjectStoreServiceException {
		final DownloadPlugin downloadPlugin = downloadPluginEnumerator.get(plugin);
		if ((basePath != null) && (basePath.isEmpty() == false)) {
			downloadPlugin.setBasePath(basePath);
		}

		final Iterable<String> urlInfo = resultSetClientFactory.getClient(epr);
		final BlockingQueue<String> itemsQueue = Queues.newArrayBlockingQueue(1024);
		final ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
		final ObjectStore objStore = objectStoreDao.getObjectStore(objectStoreID);

		final List<Future<DownloadReportMap>> responses = Lists.newArrayList();
		final DownloadReportMap pluginReport = new DownloadReportMap();
		pluginReport.setStatus(true);

		if (regularExpression != null) {
			downloadPlugin.setRegularExpression(regularExpression);
		}

		for (int i = 0; i < numberOfThreads; i++) {
			responses.add(executor
					.submit(new DownloadWorker(itemsQueue, objStore, Protocols.valueOf(protocol), mimeType, connectTimeoutMs, readTimeoutMs, sleepTimeMs,
					new Function<String, DownloadItem>() {

				@Override
				public DownloadItem apply(final String input) {
					if (input == null) {
						log.error("Input is null");
						return null;
					}
					if (input.equals(DownloadServiceImpl.END_QUEUE_STRING)) return DownloadServiceImpl.END_QUEUE;

					DownloadItem di = null;
					try {
						di = DownloadItem.newObjectfromJSON(input);

						if (downloadPlugin.retrieveUrl(di) == null) {
							di.setUrl(null);
							di.setOriginalUrl(null);
						}
						return di;
					} catch (Throwable e) {
						reportException(pluginReport, di, e);
						log.error("Exception on transform item :" + input, e);
						return null;
					}
				}
			})));
		}

		int i = 0;
		int null_found = 0;
		if (urlInfo != null) {
			for (final String downloadItem : urlInfo) {
				if (downloadItem != null) {
					null_found = 0;
					if ((i++ % 1000) == 0) {
						log.debug("Read " + i);
					}
					try {
						itemsQueue.put(downloadItem);
					} catch (final Exception e) {
						log.error("An error occurred while populating the download items queue: " + Joiner.on("\tat ").join(e.getStackTrace()));
					}
				} else {
					if (null_found++ > MAX_NUM_FOUND) {
						break;
					}
				}

			}
		}

		try {
			itemsQueue.put(DownloadServiceImpl.END_QUEUE_STRING);
		} catch (final InterruptedException e) {
			log.error("An error occurred adding the loop terminator: " + Joiner.on("\tat ").join(e.getStackTrace()));
		}

		final DownloadReportMap resultMap = getDownloadReportMap(responses, pluginReport);
		executor.shutdown();
		return resultMap;
	}

	private DownloadReportMap getDownloadReportMap(final List<Future<DownloadReportMap>> responses, final DownloadReportMap pluginReport) {
		final DownloadReportMap resultMap = new DownloadReportMap();
		resultMap.setStatus(true);

		for (final Future<DownloadReportMap> currentResponse : responses) {
			try {
				final DownloadReportMap currentMap = currentResponse.get();

				mergeReport(resultMap, currentMap);

				log.info("Status " + currentMap.getStatus());
				resultMap.setStatus(resultMap.getStatus() && currentMap.getStatus());
				resultMap.setTotalDownloaded(currentMap.getTotalDownloaded() + resultMap.getTotalDownloaded());

			} catch (final Exception e) {
				log.error(e);
				resultMap.setStatus(false);
			}
		}
		mergeReport(resultMap, pluginReport);
		return resultMap;
	}

	private void mergeReport(final DownloadReportMap resultMap, final DownloadReportMap currentMap) {
		for (final String key : currentMap.keySet()) {
			if (!resultMap.containsKey(key)) {
				resultMap.put(key, currentMap.get(key));
			} else {
				final DownloadReport currentReport = currentMap.get(key);
				resultMap.get(key).incrementError(currentReport.getNumberOfOccurrences());
			}
			resultMap.setTotalDownloaded(resultMap.getTotalDownloaded() + currentMap.getTotalDownloaded());
			resultMap.setStatus(resultMap.getStatus() & currentMap.getStatus());
		}
	}
}
