package org.apache.slide.projector.i18n;

import java.io.InputStream;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.i18n.XMLMessageProvider;
import org.apache.slide.projector.Projector;
import org.apache.slide.projector.application.Application;
import org.apache.slide.projector.application.ApplicationListener;
import org.apache.slide.projector.repository.RepositoryException;
import org.apache.slide.projector.value.Streamable;
import org.apache.slide.projector.value.URI;
import org.apache.slide.projector.value.URIValue;
import org.apache.webdav.lib.Subscriber;

public class LocalizationManager implements ApplicationListener, Subscriber {
    private static Logger logger = Logger.getLogger(LocalizationManager.class.getName());

    private final static LocalizationManager localizationManager = new LocalizationManager();
    
    public static LocalizationManager getInstance() {
        return localizationManager;
    }
    
    public void install(String type, URI applicationUri, URI configurationUri) {
    	if ( type == Application.MESSAGES ) {
            try {
                InputStream messages = ((Streamable)Projector.getRepository().getResource(configurationUri, Projector.getCredentials())).getInputStream();
                XMLMessageProvider.install(configurationUri.toString(), messages);
            } catch (RepositoryException e) {
                logger.log(Level.SEVERE, "Failed to intall messages with URI="+configurationUri+", skipping...");
            }
    	}
    }
    
    public void uninstall(String type, URI applicationUri, URI configurationUri) {
    	if ( type == Application.MESSAGES ) {
    	    XMLMessageProvider.uninstall(configurationUri.toString());
    	}
    }
    
    public void update(String type, URI applicationUri, URI configurationUri) {
    	if ( type == Application.MESSAGES ) {
            try {
                InputStream messages = ((Streamable)Projector.getRepository().getResource(configurationUri, Projector.getCredentials())).getInputStream();
                XMLMessageProvider.update(configurationUri.toString(), messages);
            } catch (RepositoryException e) {
                logger.log(Level.SEVERE, "Failed to update messages with URI="+configurationUri+", skipping...");
            }
    	}
    }

	public void notify(String uri, Map information) {
		URI messageUri = new URIValue(uri);
        try {
            InputStream messages = ((Streamable)Projector.getRepository().getResource(new URIValue(uri), Projector.getCredentials())).getInputStream();
            XMLMessageProvider.uninstall(uri);
            XMLMessageProvider.install(uri.toString(), messages);
        } catch (RepositoryException e) {
            logger.log(Level.SEVERE, "Failed to upate messages with URI="+uri+", skipping...");
        }
	}
}