/*
 * Copyright 2020 ETSI
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors 
 *    may be used to endorse or promote products derived from this software without 
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package fr.mines_stetienne.ci.saref.utils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.mines_stetienne.ci.saref.Main;
import fr.mines_stetienne.ci.saref.SAREF;
import fr.mines_stetienne.ci.sparql_generate.stream.LocationMapperAccept;
import fr.mines_stetienne.ci.sparql_generate.stream.SPARQLExtStreamManager;

/**
 *
 * @author Maxime Lefrançois
 *
 */
public class StreamManagerFactory {

	private static final Logger LOG = LoggerFactory.getLogger(StreamManagerFactory.class);

	private static final String BASE_DOC = SAREF.BASE + "documentation/";

	/**
	 * Initialize StreamManager from the pipeline documentation files, overriden by
	 * the files in the documentation directory of directory
	 * 
	 * @param directory
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static SPARQLExtStreamManager get(File directory) {
		SPARQLExtStreamManager streamManager = SPARQLExtStreamManager.makeStreamManager();
		LocationMapperAccept mapper = new LocationMapperAccept();

		// set mapper for saref-pipeline src/documentation directory
		try {
			URI uri = Main.class.getClassLoader().getResource("documentation").toURI();
			boolean isJar = uri.getScheme().equals("jar");
			Path dirPath;
			if (isJar) {
				FileSystem fileSystem;
				try {
					fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
				} catch(FileSystemAlreadyExistsException ex) {
					fileSystem = FileSystems.getFileSystem(uri);
				}
				dirPath = fileSystem.getPath("/documentation");
			} else {
				dirPath = Paths.get(uri);
			}
			walk(dirPath, isJar, mapper);
		} catch (IOException | URISyntaxException ex) {
			LOG.warn("Error while creating the StreamManager", ex);
		}

		if (directory != null) {
			// override with local files in documentation directory
			try {
				Path dirPath = Paths.get(new File(directory, "documentation").toURI());
				walk(dirPath, false, mapper);
			} catch (IOException ex) {
				LOG.warn("Error while creating the StreamManager", ex);
			}
		}

		streamManager.setLocationMapper(mapper);
		return streamManager;
	}

	/**
	 * Initialize StreamManager from the pipeline documentation files
	 * 
	 * @param directory
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static SPARQLExtStreamManager get() {
		return get(null);
	}

	private static void walk(Path dirPath, boolean isJar, LocationMapperAccept mapper) throws IOException {
		if(!Files.exists(dirPath)) {
			return;
		}
		Files.walk(dirPath).forEach((p) -> {
			String relativePath = dirPath.relativize(p).toString().replace("\\", "/");
			String fileurl = BASE_DOC + relativePath;
			if (isJar) {
				mapper.addAltEntry(fileurl, p.toString().substring(1));
			} else {
				mapper.addAltEntry(fileurl, p.toString());
			}
		});
	}
}
