package eu.dnetlib.data.objectstore;

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 java.util.function.Function;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import eu.dnetlib.data.objectstore.connector.ObjectStore;
import eu.dnetlib.data.objectstore.connector.ObjectStoreDao;
import eu.dnetlib.data.objectstore.worker.DownloadWorker;
import eu.dnetlib.enabling.resultset.client.ResultSetClient;
import eu.dnetlib.rmi.common.ResultSet;
import eu.dnetlib.rmi.data.DownloadItem;
import eu.dnetlib.rmi.data.DownloadPlugin;
import eu.dnetlib.rmi.data.ObjectStoreServiceException;
import eu.dnetlib.rmi.data.Protocols;
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);

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

	/**
	 * The result set client factory.
	 */
	@Autowired
	private ResultSetClient resultSetClient;

	/**
	 * 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 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 ObjectStoreServiceException {
		final DownloadPlugin downloadPlugin = downloadPluginEnumerator.get(plugin);
		if ((basePath != null) && (basePath.isEmpty() == false)) {
			downloadPlugin.setBasePath(basePath);
		}

		final Iterable<String> urlInfo = resultSetClient.iter(ResultSet.fromJson(epr), String.class);
		final BlockingQueue<String> itemsQueue = Queues.newArrayBlockingQueue(numberOfThreads * 5);
		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);
		}
		final Function<String, DownloadItem> applyDowunloadPlugin = input -> {
			if (input == null) {
				log.error("Input is null");
				return null;
			}
			if (input.equals(DownloadIntoObjectStoreAction.END_QUEUE_STRING)) return DownloadIntoObjectStoreAction.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;
			}
		};

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

		int i = 0;
		if (urlInfo != null) {
			for (final String downloadItem : urlInfo) {
				if (downloadItem != null) {
					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()));
					}
				}
			}
		}

		try {
			itemsQueue.put(DownloadIntoObjectStoreAction.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());
		}
	}
}
