package org.wikiwebserver.distribute.se;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;

public class ResourceManager implements Runnable {

	private static final String bundleName = "org.wikiwebserver.distribute.se.resources";
	private static ResourceBundle resources;
	
	public void run() {
		
	    ResourceBundle.Control control = new XMLResourceBundleControl();
	    
        String language = ConfigManager.getString("Language");	    
	    String country = ConfigManager.getString("Country");
	    
	    if (language == null) {
	        language = Locale.getDefault().getLanguage();
	        if (country == null) {
	            country = Locale.getDefault().getCountry();
	        }	        
	    }

	    if (country == null) Locale.setDefault(new Locale(language));
	    else Locale.setDefault(new Locale(language, country));
	    
	    
        ConfigManager.setString("Country", country);
        ConfigManager.setString("Language", language);	
        
	    resources = ResourceBundle.getBundle(bundleName, control);

		synchronized (this) {
			notifyAll();
		}
	}
	
	public static String getString(String property) {
	    try {
	        return resources.getString(property);
	    } catch (MissingResourceException ex) {
	        return "[" + property + "]";
	    }
	}
	
    public static Image getCenteredImage(String path, int width, int height) {
        
        Image image = getImage(path);
        
        BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaled.createGraphics();
        int xoffset = (width - image.getWidth(null)) / 2;
        int yoffset = (height - image.getHeight(null)) / 2;
        g2d.drawImage(image, xoffset, yoffset, null);

        return scaled;
    }	
    
    public static Image getImage(String path) {
        return getImageIcon(path).getImage();        
    }
    
    public static ImageIcon getImageIcon(String path) {
        URL imgURL = ResourceManager.class.getResource(path);
        return new ImageIcon(imgURL);      
    }
}

