/*
 * Copyright 2004-2005 The Trix Development Team.
 *
 * Licensed 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.trix.cuery.filter;

import org.w3c.css.sac.CSSException;
import org.w3c.dom.Element;

/**
 * DOCUMENT.
 * 
 * @author <a href="mailto:Teletha.T@gmail.com">Teletha Testarossa</a>
 * @version $ Id: AbstractNumeralFilter.java,v 1.2 2005/08/04 18:41:31 Teletha Exp $
 */
public abstract class AbstractNumeralFilter implements Filter {

    /** The actual argument expression. */
    protected String argument;

    /** The cardinal number. */
    private int a = 0;

    /** The cardinal number. */
    private int b = 0;

    /**
     * Create AbstractNumeralFilter instance.
     * 
     * @param argument An argument.
     * @throws CSSException If the argument is invalid pattern.
     */
    public AbstractNumeralFilter(String argument) throws CSSException {
        // check null
        if (argument == null || argument.length() == 0) {
            throw new CSSException("This argument is null.");
        }
        this.argument = argument;

        // cehck even
        if (argument.equals("even")) {
            a = 2;
            return;
        }

        // check odd
        if (argument.equals("odd")) {
            a = 2;
            b = 1;
            return;
        }

        int pos = argument.indexOf("n");

        if (pos == -1) {
            try {
                b = Integer.parseInt(argument);
            } catch (NumberFormatException e) {
                throw new CSSException("This argument format is invalid.");
            }
        } else {
            a = parseInt(argument.substring(0, pos), 1);
            b = parseInt(argument.substring(pos + 1), 0);
        }

        // check b range
        if (b < 0) {
            throw new CSSException("The argument 'b' must be positive.");
        }
    }

    /**
     * Parse string value to int value.
     * 
     * @param value A string value.
     * @param def A default value.
     * @return A parsed int value.
     */
    private int parseInt(String value, int def) {
        // check null
        if (value == null || value.length() == 0) {
            return def;
        }

        if (value.equals("+")) {
            return 1;
        }

        if (value.equals("-")) {
            return -1;
        }

        if (value.charAt(0) == '+') {
            value = value.substring(1);
        }
        return Integer.parseInt(value);
    }

    /**
     * @see org.trix.cuery.filter.Filter#accept(org.w3c.dom.Element)
     */
    public boolean accept(Element target) {
        int current = b;
        int position = getPosition(target);

        // check negative position
        if (position < 1) {
            return false;
        }

        while (true) {
            // not allow negative
            if (current < 0) {
                break;
            }

            // check position
            if (current == position) {
                return true;
            }

            // check loop
            if (a == 0 || (a > 0 && current > position) || (a < 0 && current < position)) {
                break;
            }
            current = current + a;
        }
        return false;
    }

    /**
     * @see org.trix.cuery.filter.Filter#getSpecificity()
     */
    public int getSpecificity() {
        return 10;
    }

    /**
     * @see org.w3c.css.sac.Condition#getConditionType()
     */
    public short getConditionType() {
        return SAC_POSITIONAL_CONDITION;
    }

    /**
     * @see org.w3c.css.sac.Selector#getSelectorType()
     */
    public short getSelectorType() {
        return SAC_CONDITIONAL_SELECTOR;
    }

    /**
     * Return the element position.
     * 
     * @param target A target element.
     * @return A position.
     */
    protected abstract int getPosition(Element target);
}
