/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */
package com.icesoft.net.messaging;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class AbstractMessageHandler
implements MessageHandler {
    private static final Logger LOGGER = Logger.getLogger(AbstractMessageHandler.class.getName());

    protected final Map<Callback, MessageSelector> callbackMap = new HashMap<Callback, MessageSelector>();

    protected MessageSelector messageSelector;

    protected AbstractMessageHandler() {
        this(null);
    }

    protected AbstractMessageHandler(final MessageSelector messageSelector) {
        this.messageSelector = messageSelector;
    }

    public void addCallback(final Callback callback) {
        this.addCallback(callback, null);
    }

    public void addCallback(final Callback callback, final MessageSelector messageSelector) {
        if (callback != null) {
            synchronized (callbackMap) {
                callbackMap.put(callback, messageSelector);
            }
        }
    }

    public MessageSelector getMessageSelector() {
        return messageSelector;
    }

    public void removeCallback(final Callback callback) {
        if (callback != null && callbackMap.containsKey(callback)) {
            synchronized (callbackMap) {
                if (callbackMap.containsKey(callback)) {
                    callbackMap.remove(callback);
                }
            }
        }
    }

    public void setMessageSelector(final MessageSelector messageSelector) {
        this.messageSelector = messageSelector;
    }

    protected Callback[] getCallbacks(final Message message) {
        List<Callback> _callbackList = new ArrayList<Callback>();
        if (message != null) {
            synchronized (callbackMap) {
                for (Map.Entry<Callback, MessageSelector> _entry : callbackMap.entrySet()) {
                    MessageSelector _messageSelector = _entry.getValue();
                    if (_messageSelector == null || _messageSelector.matches(message)) {
                        _callbackList.add(_entry.getKey());
                    }
                }
            }
        }
        return _callbackList.toArray(new Callback[_callbackList.size()]);
    }
}
