package com.ttv.acs.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

public class FileURIConverter {
	
	/* Map of file URI to linux mount paths */
	private Map<String, String> fileURIPathMap = new HashMap<String, String>();

	/* Map of linux mount paths to file URI */
	private Map<String, String> mountMap = new HashMap<String, String>();

	/* The Resource Path */
	private static final String RESOURCE_PATH = "/fileURIConverter.properties";

	private static Logger logger = Logger.getLogger(FileURIConverter.class);
	
	public FileURIConverter() {
		this.loadPathConfiguration();
	}

	/* Loads the Path Configuration */
	private synchronized void loadPathConfiguration() {
		this.mountMap.clear();
		this.fileURIPathMap.clear();

		try {
			InputStream stream = this.getClass().getResourceAsStream(RESOURCE_PATH);
			Properties config = new Properties();
			config.load(stream);

			for (Object keyObject : config.keySet()) {
				String mountPath = ((String) keyObject).trim();
				String fileURI = config.getProperty(mountPath).trim();
				logger.debug(mountPath+" = "+ fileURI);
				this.mountMap.put(mountPath, fileURI);
				this.fileURIPathMap.put(fileURI, mountPath);
			}
		} catch (IOException e) {
			String msg = "Failed to load the Path configuration file: " + RESOURCE_PATH;
			throw new RuntimeException(msg, e);
		}
	}

	/**
	 * Converts a UNC style Path to the Unix style Path
	 * 
	 * @param uri
	 *            The File URI path
	 * @return null if cannot convert else return converted linux path
	 */
	public String convertURIToUnix(String uri) {
		if (uri == null)
			return null;

		String unixPath = this.replacePath(uri, true);
		return unixPath;
	}

	/**
	 * Converts a Unix style Path to the UNC style Path
	 * 
	 * @param unixPath
	 *            The Unix Path
	 * @return null if cannot convert else return the converted file URI path
	 
	 */
	public String convertUnixToURI(String unixPath) {
		if (unixPath == null)
			return null;

		String uriPath = this.replacePath(unixPath, false);
		return uriPath;
	}

	/* Replace the file URI with the Mount Path or vice versa */
	private String replacePath(String path, boolean isURIPath) {
		StringBuffer sb = new StringBuffer(path.trim());
		Map<String, String> pathMap = (isURIPath) ? this.fileURIPathMap : this.mountMap;
		for (String mappedPath : pathMap.keySet()) {
			if (path.startsWith(mappedPath)) {
				sb.replace(0, mappedPath.length(), pathMap.get(mappedPath));
				return sb.toString();
			}
		}
		return null;
	}
}
