/*
 * 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 com.scytl.products.ov.commons.infrastructure.remote.client.NodeIdentifier;

import javax.security.auth.Destroyable;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author jbarrio
 * @date 15/12/16
 *
 * Copyright (C) 2016 Scytl Secure Electronic Voting SA
 *
 * All rights reserved.
 */
class KeystorePasswordsReaderImpl extends AbstractKeystorePasswordsReader implements Destroyable {

	private static final String DEFAULT_FILENAME_PREFIX = "keystore-passwords";

	protected KeystorePasswordsReaderImpl(final KeystoreResources keystoreResources, final NodeIdentifier nodeIdentifier) {
		super( keystoreResources, DEFAULT_FILENAME_PREFIX, nodeIdentifier );
	}

	static KeystorePasswordsReaderImpl getInstance(final KeystoreResources keystoreResources, final NodeIdentifier nodeIdentifier) {
		return new KeystorePasswordsReaderImpl( keystoreResources, nodeIdentifier );
	}

	@Override
	public void destroy() {
		if (this.destroyed) {
			final String errorMsg = "Object already destroyed";
			LOG.debug( errorMsg );
		} else {
			final URL propertiesURL = this.resources.getResourceURL( this.passwordsPath );
			if (propertiesURL == null) {
				LOG.info( "No destroyable file at {}",  this.passwordsPath);
			} else {
				final URI propertiesURI;
				try {
					propertiesURI = propertiesURL.toURI();
					final Path passwordsPath = Paths.get( propertiesURI );
					if (passwordsPath == null) {
						final String errorMsg = "No destroyable file at " + passwordsPath;
						LOG.info( errorMsg );
					} else {
						try {
							Files.delete( passwordsPath );
							this.destroyed = true;
						} catch (IOException ioE) {
							LOG.info("Could not destroy file {}: {}", passwordsPath, ioE.getMessage(), ioE);
						}
					}
				} catch (final URISyntaxException isE) {
					LOG.info("Error trying to destroy file.", isE);
				}
			}
		}
	}

}