/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.keystore;

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

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * @author jbarrio
 * @date 20/12/16
 *
 * Copyright (C) 2016 Scytl Secure Electronic Voting SA
 *
 * All rights reserved.
 */
abstract class AbstractKeystoreResources implements KeystoreResources {

	protected static final Logger LOG = LoggerFactory.getLogger("std");

	private final Class<?> locationHookClass;
	private final String resourcesPath;
	private final KeystoreProperties keystoreProperties;

	protected AbstractKeystoreResources(final Class<?> locationHookClass, final String resourcesPath, final String keystorePropertiesPath) {
		this.locationHookClass = locationHookClass;
		this.resourcesPath = resourcesPath;
		this.keystoreProperties = this.readKeystoreProperties( keystorePropertiesPath );
	}

	private KeystoreProperties readKeystoreProperties(final String keystorePropertiesPath) {
		final String resourcePath = this.getResourcePath( keystorePropertiesPath );
		final Properties properties = new Properties();
		try (final InputStream inputStream = this.getResourceAsStream( resourcePath )) {
			if (inputStream == null) {
				final String errorMsg = "Keystore properties not found at " + resourcePath;
				LOG.info( errorMsg );
			} else {
				properties.load( inputStream );
			}
		} catch (final IOException ioE) {
			LOG.error( "Error while trying to initialize keystore properties from {} : {}", resourcePath, ioE.getMessage(), ioE);
		}
		return KeystoreProperties.read( properties );
	}

	@Override
	public String getResourcePath(final String resourceName) {
		return this.resourcesPath + resourceName;
	}

	@Override
	public URL getResourceURL(final String resourcePath) {
		return this.locationHookClass.getResource(resourcePath);
	}

	@Override
	public InputStream getResourceAsStream(final String resourcePath) {
		final URL resourceURL = this.locationHookClass.getResource( resourcePath );
		if (resourceURL == null) {
			final String errorMsg = "Resource not found at " + resourcePath;
			LOG.info( errorMsg );
			return null;
		} else {
			return this.locationHookClass.getResourceAsStream( resourcePath );
		}
	}

	@Override
	public KeystoreProperties getKeystoreProperties() {
		return this.keystoreProperties;
	}

}
