package usda.weru.resources;

import java.awt.Image;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 

/**
 *
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class Resources {

    private static final Logger LOGGER = LogManager.getLogger(Resources.class);

    /**
     *
     * @param filename
     * @return
     */
    public static final Image getImage(String filename) {
        try {
            URL url = Resources.class.getResource(filename);
            if(url == null)
            {
                LOGGER.error("URL for image " + filename + " returned null.  Replacing with weruface.gif.");
                return getImage("weruface.gif");
            }
            return Toolkit.getDefaultToolkit().createImage(Resources.class.getResource(filename));
        } catch (Exception e) {
            LOGGER.warn("Unable to load image. " + filename, e);
            return null;
        }
    }

    /**
     *
     * @param filename
     * @return
     */
    public static final Icon getIcon(String filename) {
        Image res = getImage(filename);
        if(res == null) return null;
        else return new ImageIcon(res);
    }
    /**
     * Adds a file stream based on the filename passed in.  Looks in the certs folder
     * in the install directory.
     * @param filename
     * @return
     * @throws FileNotFoundException 
     */
    public static final InputStream getCertStream(String filename) throws FileNotFoundException
    {
        //Looks for the inputted file in the certs directory in the weps.install directory.
        String path = "certs/" + filename;
        File input = new File(path);
        return new BufferedInputStream(new FileInputStream(input));
    }
}
