/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activeblaze.impl.destination;

import org.apache.activeblaze.wire.Buffer;


/**
 * Matches a Destination Subject to wildcards
 */
public final class DestinationMatch {
    static final byte MATCH_ELEMENT = '*';
    static final byte MATCH_ALL = '>';
    //static final byte[] DELIMETERS = { '.', '/', '|' };
    static final byte DELIMETER = '.';

    /**
     * See if the destination matches with wild cards
     *
     * @return true if its a match
     */
    public static boolean isMatch(String destination, String match) {
        return isMatch(new Buffer(destination), new Buffer(match));
    }

    /**
     * See if the destination matches with wild cards
     *
     * @return true if its a match
     */
    public static boolean isMatch(Buffer destination, String match) {
        return isMatch(destination, new Buffer(match));
    }

    /**
     * See if the destination matches with wild cards
     *
     * @return true if its a match
     */
    public static boolean isMatch(String destination, Buffer match) {
        return isMatch(new Buffer(destination), match);
    }

    /**
     * See if the destination matches with wild cards
     *
     * @return true if its a match
     */
    public static boolean isMatch(Buffer destination, Buffer match) {
        boolean result = true;
        boolean matchAll = false;
        if (destination == null && match == null) {
            return true;
        }
        if (destination == null || match == null) {
            return false;
        }
        int destinationOffset = 0;
        int matchOffset = 0;
        while (destinationOffset < destination.length
                && matchOffset < match.length) {
            byte matchByte = match.data[match.offset + matchOffset];
            byte destinationByte = destination.data[+destination.offset + destinationOffset];
            if (matchByte != destinationByte || matchByte == MATCH_ALL || destinationByte == MATCH_ALL
                    || matchByte == MATCH_ELEMENT || destinationByte == MATCH_ELEMENT) {
                if (matchByte == MATCH_ALL || destinationByte == MATCH_ALL) {
                    matchAll = true;
                    break;
                } else if ((matchByte == MATCH_ELEMENT || destinationByte == MATCH_ELEMENT)
                        && (isMatchElement(match, matchOffset, match.length) || isMatchElement(destination,
                        destinationOffset, destination.length))) {
                    if (containsDelimeter(destination, destinationOffset, destination.length) == false
                            && containsDelimeter(match, matchOffset, match.length) == false) {
                        break;
                    } else {
                        matchOffset = offsetToNextToken(match, matchOffset, match.length);
                        destinationOffset = offsetToNextToken(destination, destinationOffset, destination.length);
                        continue;
                    }
                } else {
                    result = false;
                    break;
                }
            }
            matchOffset++;
            destinationOffset++;
        }
        if (result
                && (match.length != destination.length && matchOffset != match.length || destinationOffset != destination.length)
                && !matchAll) {
            result = isMatchAll(match, matchOffset, match.length)
                    || isMatchAll(destination, destinationOffset, destination.length);
        }
        return result;
    }

    static boolean isMatchAll(Buffer str, int offset, int count) {
        boolean result = false;
        if (str != null && offset < str.length) {
            byte offByte = str.byteAt(offset);
            byte offBytePlusOne = (byte) ((offset + 1) < str.length ? str.byteAt(offset + 1) : ' ');
            if (offset + 1 < str.length && DELIMETER == offByte) {
                if (offBytePlusOne == MATCH_ALL) {
                    result = true;
                }
            } else if ((offByte == MATCH_ALL || offByte == MATCH_ELEMENT)
                    && (isWhiteSpace(str, offset + 1, count) || DELIMETER == offBytePlusOne || offset + 1 == str.length)) {
                result = true;
            }
        }
        return result;
    }

    static boolean isMatchElement(Buffer str, int offset, int count) {
        boolean result = false;
        if (str.byteAt(offset) == MATCH_ELEMENT) {
            if (offset == 0 || str.byteAt(offset - 1) == DELIMETER) {
                result = ((offset + 1) >= str.length) || str.byteAt(offset + 1) == DELIMETER
                        || isWhiteSpace(str, offset + 1, count);
            }
        }
        return result;
    }

    private static boolean isWhiteSpace(Buffer str, int offset, int len) {
        boolean result = true;
        while ((offset < len)) {
            if (str.byteAt(offset++) > ' ') {
                result = false;
                break;
            }
        }
        return result;
    }

    static int offsetToNextToken(Buffer str, int offset, int len) {
        while (offset < len) {
            if (str.byteAt(offset) == DELIMETER)
                break;
            offset++;
        }
        return offset;
    }

    static int offsetToNextElement(Buffer str, int offset, int len) {
        int result = -1;
        int count = offset;
        while (count < len) {
            if (str.byteAt(count) == DELIMETER) {
                result = ++count;
                // check for double placed elements ...
                while (count < len && str.byteAt(count) == DELIMETER) {
                    result = ++count;
                }
                break;
            }
            count++;
        }
        return result;
    }

    private static boolean containsDelimeter(Buffer str, int offset, int len) {
        boolean result = false;
        while (offset < len) {
            if (str.byteAt(offset++) == DELIMETER) {
                result = true;
                break;
            }
        }
        return result;
    }

}
