/*
 * 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.tallying.path;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * {@link PathResolver} implementation that resolves a path by looking for it in
 * the resource folder
 */
public class ResourcePathResolver implements PathResolver {

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

    @Override
    public Path resolve(final String path) {
        // When calling getResource, the provided path must start with "/"
        String normPath = (path.startsWith("/") ? "" : "/") + path;
        URL url = getClass().getResource(normPath);
        if (url == null) {
            LOG.warn("Error resolving path: " + path);
            return null;
        }
        try {
            return Paths.get(url.toURI());
        } catch (URISyntaxException e) {
            LOG.warn("Error resolving path: " + path, e);
        }
        return null;
    }
}
