/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.fabric;

import java.util.regex.Pattern;

/**
 * Represents a subscription to a message channel which is interested in any symbols matching an internal
 * <code>Pattern</code>.
 * <p>
 * MTS: Safe.
 *
 * @author Alex Leigh
 */
public class PatternMessageSubscription<E> implements MessageSubscription<E> {
    private final Pattern pattern;
    private final MessageReceiver<E> subscriber;

    /**
     * Create a new subscription. If the subscription is to be for all symbols, <code>null</code> may be provided
     * for the pattern.
     *
     * @param symbolPattern
     * @param subscriber
     */

    public PatternMessageSubscription(final Pattern symbolPattern, final MessageReceiver<E> subscriber) {
        this.pattern = symbolPattern;
        this.subscriber = subscriber;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public MessageReceiver<E> getSubscriber() {
        return subscriber;
    }

    /**
     * Returns <code>true</code> if this subscription matches the provided symbol.
     *
     * @param symbol
     * @return
     */
    @Override
    public boolean matches(final String symbol) {
        return pattern.matcher(symbol).matches();
    }


    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final PatternMessageSubscription that = (PatternMessageSubscription) o;

        if (pattern != null ? !pattern.equals(that.pattern) : that.pattern != null) return false;
        return subscriber != null ? subscriber.equals(that.subscriber) : that.subscriber == null;

    }

    @Override
    public int hashCode() {
        int result = pattern != null ? pattern.hashCode() : 0;
        result = 31 * result + (subscriber != null ? subscriber.hashCode() : 0);
        return result;
    }
}