/*
 * 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.property;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.trix.cuery.value.CSSValue;
import org.trix.cuery.value.ValueUtil;

import org.w3c.css.sac.LexicalUnit;

/**
 * DOCUMENT.
 * 
 * @author <a href="mailto:Teletha.T@gmail.com">Teletha Testarossa</a>
 * @version $ Id: ShorthandPropertyDefinition.java,v 1.02 2005/09/10 20:50:41 Teletha Exp $
 */
public class ShorthandPropertyDefinition extends PropertyDefinition {

    /** The property definition list. */
    protected final List definitions = new ArrayList(4);

    /**
     * @see org.trix.cuery.property.PropertyDefinition#addAcceptable(java.lang.Object)
     */
    protected void addAcceptable(Object acceptable) {
        if (acceptable instanceof PropertyDefinition) {
            definitions.add(acceptable);
        } else {
            super.addAcceptable(acceptable);
        }
    }

    /**
     * @see org.trix.cuery.property.PropertyDefinition#parse(org.trix.cuery.value.CSSValue)
     */
    public Map parse(CSSValue value) {
        // check inherit
        if (value.getLength() == 1 && value.getLexicalUnitType() == LexicalUnit.SAC_INHERIT) {
            // inherit identifier is not acceptable
            if (!acceptInherit()) {
                return null;
            }

            Map map = new HashMap(definitions.size());

            for (int i = 0; i < definitions.size(); i++) {
                PropertyDefinition definition = (PropertyDefinition) definitions.get(i);
                Map result = definition.parse(value);

                // check result
                if (result == null) {
                    continue;
                }

                map.put(definition.getName(), value);
                map.putAll(result);
            }
            return map;
        }

        Map map = new HashMap(definitions.size());
        CSSValue current = value;

        boolean[] flags = new boolean[definitions.size()];
        Arrays.fill(flags, false);

        // parse and validate the sequence of css values
        while (current != null) {
            int type = current.getLexicalUnitType();

            // inherit identifier is forbidden in the shorthand property
            if (type == LexicalUnit.SAC_INHERIT) {
                return null;
            }

            // skip slash and comma
            if (type == LexicalUnit.SAC_OPERATOR_SLASH) {
                current = current.getNextValue();
                continue;
            }

            if (type == LexicalUnit.SAC_OPERATOR_COMMA) {
                break;
            }

            // investigat each definition
            for (int i = 0; i < definitions.size(); i++) {
                // use only unused definition
                if (!flags[i]) {
                    Map result = null;
                    PropertyDefinition definition = (PropertyDefinition) definitions.get(i);
                    boolean isShorthand = definition instanceof ShorthandPropertyDefinition;

                    if (isShorthand) {
                        result = definition.parse(ValueUtil.singleValue(current));
                    } else {
                        result = definition.parse(current);
                    }

                    // this dedinition is suitable
                    if (result != null) {
                        // store current property and additional properties
                        // additional properties can override the current property
                        map.put(definition.getName(), current);
                        map.putAll(result);

                        // this definition is checked as used
                        flags[i] = true;

                        // step to next value
                        current = current.getNextValue();

                        // If additional properties exits, some following values are already parsed.
                        // So we should pass them to avoid parsing error in future.
                        if (!isShorthand && result.size() > 1) {
                            for (int pass = 0; pass < result.size() - 1; pass++) {
                                // if current value is null, through out now
                                if (current == null) {
                                    break;
                                }
                                current = current.getNextValue();
                            }
                        }
                        // all steps are done about this value, move to the next analysis
                        break;
                    }
                }

                // To our regret, the current value doesn't apply to this definition.
                // Try to next definition, good luck.

                // The current value doesn't apply to all the definitions, so this is invalid.
                if (i == definitions.size() - 1) {
                    return null;
                }
            }
        }

        // validate final result
        return validate(map);
    }

    /**
     * This method is executed after the method 'parse'. The purpose of this method are validating
     * value and filling ommitted properties.
     * 
     * @param result A parsing result.
     * @return A validating and filling result.
     */
    protected Map validate(Map result) {
        return result;
    }

    /**
     * Helper method to check this definition accepts the inherit identifier.
     * 
     * @return A result.
     */
    private boolean acceptInherit() {
        for (int i = 0; i < acceptables.size(); i++) {
            if (acceptables.get(i).equals(CSSValue.INHERIT)) {
                return true;
            }
        }
        return false;
    }

}
