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

import com.scytl.products.ov.config.tenant.ConfigurationInput;
import com.scytl.products.ov.config.tenant.exception.IOUtilsServiceException;
import com.scytl.products.ov.constants.Constants;
import com.scytl.products.ov.datapacks.beans.CredentialProperties;
import com.scytl.products.ov.utils.ConfigObjectMapper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
public class IOUtilsService {


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

        ConfigObjectMapper configObjectMapper = new ConfigObjectMapper();
        ConfigurationInput configurationInput = null;
        try {
            configurationInput = configObjectMapper.fromJSONFileToJava(new File(url.toURI()), ConfigurationInput.class);
        } catch (IOException | URISyntaxException e) {
            throw new IOUtilsServiceException("Error reading the keys_config.json file", e);
        }

        return configurationInput.getTenantRootCA();
    }


    public void createOutputDirectory(final Path outputPath) {
        try {
            Files.createDirectories(outputPath);
        } catch (IOException e) {
           throw new IOUtilsServiceException("Error generating the outputDirectoy", e);
        }
    }

}