package com.lrother.ressync.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.lrother.ressync.data.ResourceEntry;

public class ResourceFileReader {
	
	private static Logger logger = LogManager.getLogger(ResourceFileReader.class);
	
	private File resourceFile;
	
	public ResourceFileReader(File resourceFile) {
		this.resourceFile = resourceFile;
	}

	public List<ResourceEntry> readList() throws IOException {
		Properties properties = loadPropertiesFromResourceFile();
		return mapPropertiesToList(properties);
	}

	private List<ResourceEntry> mapPropertiesToList(Properties properties) {
		List<ResourceEntry> resourceEntries = new ArrayList<>();
		
		for (Object keyObj : properties.keySet()) {
			String key = (String)keyObj;
			resourceEntries.add(new ResourceEntry(key, properties.getProperty(key)));
		}
		return resourceEntries;
	}

	/**
	 * Loads properties from resource file. Null is never returned.
	 * 
	 * @return Properties object, never null.
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private Properties loadPropertiesFromResourceFile()
			throws IOException, FileNotFoundException {
		
		Properties properties = new Properties();
		
		try (
			FileInputStream resFileInputStream = new FileInputStream(resourceFile);
		) {
			properties.load(resFileInputStream);
			logger.debug("Properties successfully loaded from: " + resourceFile.getAbsolutePath());
		}
		
		return properties;
	}
	
	public Map<String, ResourceEntry> readMap() throws IOException {
		Properties properties = loadPropertiesFromResourceFile();
		return mapPropertiesToMap(properties);
	}

	private Map<String, ResourceEntry> mapPropertiesToMap(Properties properties) {
		Map<String, ResourceEntry> resourceEntries = new HashMap<String, ResourceEntry>();
		
		for (Object keyObj : properties.keySet()) {
			String key = (String)keyObj;
			resourceEntries.put(key, new ResourceEntry(key, properties.getProperty(key)));
		}
		
		return resourceEntries;
	}

}
