/*
 * 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.sdm.application.service;

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.scytl.products.ov.commons.infrastructure.remote.client.NodeIdentifier;
import com.scytl.products.ov.keystore.KeystoreReader;
import com.scytl.products.ov.keystore.KeystoreReaderFactory;
import com.scytl.products.ov.sdm.application.exception.KeyStoreServiceException;


public class KeyStoreServiceImpl  implements KeyStoreService{

    private static final String PRIVATE_KEYSTORE_PW = "private-keystore.password";

    @Value("${SDM_KEYSTORE_PASSWORD_FILE}")
    private String passwordFile;

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

    private static final NodeIdentifier THIS_NODE = NodeIdentifier.SECURE_DATA_MANAGER;

    private final KeystoreReader keystoreReader = new KeystoreReaderFactory().getInstance();

    private String password;

    private PrivateKey key;

    @PostConstruct
    public void readPrivateKey() {
        LOG.info("Trying to get Private key from proper keystore to sign requests...");

        try {
            Properties prop = new Properties();
            prop.load(new FileReader(Paths.get(passwordFile).toFile()));
            password = prop.getProperty(PRIVATE_KEYSTORE_PW);
            key = this.keystoreReader.readSigningPrivateKey( THIS_NODE, password );
			if (key == null) {
				LOG.error("Unable to create request signing key with the password stored at: {}", passwordFile);
				throw new KeyStoreServiceException(
						"Unable to create request signing key with the password stored at: " + passwordFile);
			}
		} catch (IOException e) {
			LOG.error("Failed to read keystore password from file: {}", passwordFile);
			throw new KeyStoreServiceException("Failed to read keystore password from file: " + passwordFile, e);
		}
    }

    public PrivateKey getPrivateKey() {
        return key;
    }
}
