/*
 * Created on Nov 23, 2004
 * Copyright (C) Andrea Schweer, 2004
 *
 * This file is part of the Greenstone Alerting Service.
 * Refer to the COPYING file in the base directory of this package
 * for licensing information.
 */
package org.greenstone.gsdlas;

import java.util.*;

import org.greenstone.gsdlas.profiles.Subscription;

/**
 * @author schweer
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class NotificationStore {

    private static NotificationStore instance;
    private Map eventsForSubscriptionID = new TreeMap();
    
    private NotificationStore() {
    }
    
    /**
     * @return
     */
    public static NotificationStore getInstance() {
        if (instance == null) instance = new NotificationStore();
        return instance;
    }
    
    public void add(Map event, Set subscriptions) {
        encodeValues(event);
        for (Iterator iter = subscriptions.iterator(); iter.hasNext();) {
            Subscription sub = (Subscription) iter.next();
            Integer subscriptionID = new Integer(sub.getId()); 
            if (!eventsForSubscriptionID.containsKey(subscriptionID)) {
                eventsForSubscriptionID.put(subscriptionID, new HashSet());
            }
            ((Set) eventsForSubscriptionID.get(subscriptionID)).add(event);
        }
    }

    /**
     * @param event
     */
    private void encodeValues(Map event) {
        for (Iterator iter = event.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            String value = (String) event.get(key);
            String encodedValue = value.replaceAll("&", "&amp;");
            encodedValue = encodedValue.replaceAll("<", "&lt;");
            encodedValue = encodedValue.replaceAll(">", "&gt;");
            encodedValue = encodedValue.replaceAll("\'", "&apos;");
            encodedValue = encodedValue.replaceAll("\"", "&quot;");
            
            event.put(key, encodedValue);
        }
    }

    /**
     * @param subscriptionID
     * @return
     */
    public Set getEvents(Integer subscriptionID) {
        if (eventsForSubscriptionID.containsKey(subscriptionID)) {
            return Collections.unmodifiableSet((Set) eventsForSubscriptionID.get(subscriptionID));
        }
        return new TreeSet();
    }

}
