/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.io;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.MissingResourceException;
import net.ranides.assira.reflection.util.ClassUtils;

/**
 *
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public final class ResourceUtils {
    
    private ResourceUtils() {
        /* utility class */
    }
    
    
    public static void extract(String resource, File target) throws IOException, MissingResourceException {    
        extract(ClassUtils.loader(), resource, target);
    }
    
    public static void extract(ClassLoader loader, String resource, File target) throws IOException, MissingResourceException {
        try(InputStream istream = stream(loader, resource)) {
            try(OutputStream ostream = new BufferedOutputStream(new FileOutputStream(target))) {
                IOStreams.copy(istream, ostream);
            }
        }
    }
    
    public static InputStream stream(String resource) throws IOException {
        return stream(ClassUtils.loader(), resource);
    }
    
    public static InputStream stream(ClassLoader loader, String resource) throws IOException {
        InputStream stream = loader.getResourceAsStream(resource);
        if(null==stream) {
            throw new IOException("Resource not found: " + resource);
        }
        return stream;
    }
    
    public static Reader reader(String resource, Charset charset) throws IOException {
        return reader(ClassUtils.loader(), resource, charset);
    }
    
    public static Reader reader(ClassLoader loader, String resource, Charset charset) throws IOException {
        return new InputStreamReader(stream(loader, resource), charset);
    }

}
