/*
 * 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.domain.service.utils;

import com.scytl.products.ov.commons.path.PathResolver;
import com.scytl.products.ov.datapacks.beans.CertificateParameters;
import com.scytl.products.ov.sdm.domain.service.ConfigConstants;
import java.io.IOException;
import java.nio.file.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Allows for the loading of public keys.
 */
@Component
public class SystemTenantPublicKeyLoader {

    private static final String FILENAME_PARTS_SEPARATOR = "_";

    @Autowired
    private PublicKeyLoader publicKeyLoader;

    @Autowired
    private PathResolver pathResolver;

    /**
     * Loads a public key from a file, and returns it as a string in PEM format.
     * <P>
     * Note: this method assumes that a file with the following name will exist in the 'systemkeys' directory:
     * <P>
     * <tenantID>_<service name>_<type>.pem where "service name" is a two character string, and type
     * is one of ENCRYPTION | SIGN.
     *
     * @param tenantID
     *            the tenant identifier.
     * @param serviceName
     *            a two character ID of the name of the service.
     * @return the loaded public key as a string in PEM format.
     * @throws IOException
     */
    public String load(final String tenantID, final String serviceName,
            final CertificateParameters.Type type) throws IOException {

        Path path = buildSystemTenantCertificatePath(tenantID, serviceName, type);
        return publicKeyLoader.getPublicKeyAsStringFromCertificate(path);
    }

    private Path buildSystemTenantCertificatePath(final String tenantID, final String serviceName,
            final CertificateParameters.Type type) {

		String certificateFilename = tenantID + FILENAME_PARTS_SEPARATOR + serviceName + FILENAME_PARTS_SEPARATOR
				+ type.name() + ConfigConstants.PEM;
		return pathResolver.resolve(ConfigConstants.SYSTEM_TENANT_KEYS).resolve(certificateFilename);
    }
}
