/*
 * 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.config.io;

import com.scytl.products.ov.datapacks.beans.CertificateParameters;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import com.scytl.products.ov.config.commons.exception.CredentialPropertiesProviderException;
import com.scytl.products.ov.constants.Constants;
import com.scytl.products.ov.datapacks.beans.CredentialProperties;
import com.scytl.products.ov.utils.ConfigObjectMapper;

public class CredentialPropertiesProvider {

    private ConfigurationInput configurationInput;

    public CredentialPropertiesProvider() {
        URL url = this.getClass().getResource("/" + Constants.KEYS_CONFIG_FILENAME);

        ConfigObjectMapper configObjectMapper = new ConfigObjectMapper();
        try {
            configurationInput =
                configObjectMapper.fromJSONFileToJava(new File(url.toURI()), ConfigurationInput.class);
        } catch (IOException | URISyntaxException e) {
			throw new CredentialPropertiesProviderException(
					"An error occurred while reading the internal configuration file", e);
        }
    }

    public CredentialProperties getPlatformRootCredentialPropertiesFromClassPath() {
        return configurationInput.getPlatformRootCA();
    }

    public CredentialProperties getTenantCredentialPropertiesFromClassPath() {
        return configurationInput.getTenantCA();
    }

    public CredentialProperties getSystemCredentialPropertiesFromClassPath(CertificateParameters.Type type) {
        CredentialProperties properties;

        switch (type) {
            case ENCRYPTION:
                properties = configurationInput.getSystemServicesEncryptionCert();
                break;
            case SIGN:
                properties = configurationInput.getSystemServicesSigningCert();
                break;
            default:
                throw new IllegalArgumentException(
                        "No system credential properties for type " + type.name());
        }

        return properties;
    }

    public CredentialProperties getServicesLoggingSigningCredentialPropertiesFromClassPath() {
        return configurationInput.getLoggingServicesSignerCert();
    }

    public CredentialProperties getServicesLoggingEncryptionCredentialPropertiesFromClassPath() {
        return configurationInput.getLoggingServicesEncryptionCert();
    }

    public CredentialProperties getControlComponentNodePropertiesFromClassPath() {
        return configurationInput.getControlComponentNodeCA();
    }

    public CredentialProperties getControlComponentNodeSystemEncryptionPropertiesFromClassPath() {
        return configurationInput.getControlComponentNodeSystemEncryption();
    }

}
