/*
 * Copyright 2006 Mask@ Project.
 * 
 * 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.maskat.xml.digester.rules;

import org.apache.commons.digester.Rule;
import org.maskat.framework.screendef.customize.CustomizeDef;
import org.maskat.framework.screendef.customize.IPluginComponentDef;
import org.maskat.framework.screendef.customize.PluginDefFactory;
import org.maskat.framework.screendef.customize.PluginDefUnavailableException;
import org.maskat.xml.digester.MaskatDigester;
import org.xml.sax.Attributes;

public class CustomizeComponentRule extends Rule {

	public void begin(String namespace, String name, Attributes attributes)
			throws Exception {
		MaskatDigester md = (MaskatDigester) this.getDigester();
		String prefix = (String) md.getNamespaceMap().get(namespace);
		try {
			IPluginComponentDef componentDef = PluginDefFactory.newComponentDef(name,
					namespace, prefix);
			digester.push(componentDef);

			for (int i = 0; i < attributes.getLength(); i++) {
				String attribName = attributes.getLocalName(i);
				if ("".equals(attribName)) {
					attribName = attributes.getQName(i);
				}
				String value = attributes.getValue(i);
				componentDef.setAttribute(attribName, value);
			}
			return;
		} catch (PluginDefUnavailableException e) {
			// If the component is not defined by plugin, it is deemed as
			// CustomizeDef.
		}

		CustomizeDef def = new CustomizeDef();
		digester.push(def);
		def.setName(name);
		// ここでは、マップから、namespaceURIと対応するnamespace prefixを取得
		def.setPrefix(prefix);

		for (int i = 0; i < attributes.getLength(); i++) {
			def.addAttrib(attributes.getLocalName(i), attributes.getValue(i));
		}
	}

	public void end() throws Exception {
		digester.pop();
	}
}
